在PowerShell中重写Bash脚本

时间:2013-12-08 00:11:13

标签: bash powershell

我有一个bash脚本,可以将名称,日期和位置放入示例文件中。代码看起来像这样

#/bin/bash

if [ $# -ne 2 ]; then
    echo You should give two parameters!
    exit
fi

while read line
do
    name=`echo $line | awk '{print $1}'`
    date=`echo $line  | awk '{print $2}'`
    place=`echo $line | awk '{print $3}'`
    echo `cat $1 | grep "<NAME>"|  sed -e's/<NAME>/'$name'/g'`
    echo `cat $1 | grep "<DATE>" | sed -e's/<DATE>/'$date'/g'`
    echo `cat $1 | grep "<PLACE>" | sed -e's/<PLACE>/'  $place'/g'`
    echo 
done < $2

我想用powershel写它。这是我的尝试:

if($args.count -ne 2)
{
    write-host You should give two parameters!
    return
}

$input = Get-Content $args[1]
$samplpe = Get-Content $args[0]

foreach($line in $input)
{       
        name= $line | %{"$($_.Split('\t')[1])"}
        date= $line | %{"$($_.Split('\t')[2])"}
        place= $line | %{"$($_.Split('\t')[3])"}
        write-host cat $sample | Select-String [-"<NAME>"] | %{$_ -replace "<NAME>", "$name"}`
        write-host cat $sample | Select-String [-"<NAME>"] | %{$_ -replace "<DATE>", "$date"}
        write-host cat $sample | Select-String [-"<NAME>"] | %{$_ -replace "<PLACE>", "$place"}

}

但这很有效,但我不知道为什么:S

2 个答案:

答案 0 :(得分:1)

明显的问题是这里显而易见的错字:

$samplpe = Get-Content $args[0]

除此之外,如果不知道数据是什么样子很难说,但它似乎要比它需要的复杂得多。我做这样的事情(最好猜测数据是什么样的)。

'<Name>__<Date>__<Place>' | set-content args0.txt
"NameString`tDateString`tPlacestring" | Set-Content args1.txt

$script =
{
  if($args.count -ne 2)
   {
    write-host You should give two parameters!
    return
   }

 $Name,$Date,$Place = (Get-Content $args[1]).Split("`t")

 (Get-Content $args[0]) -replace '<Name>',$name -replace '<Date>',$Date -replace '<Place>',$Place | Write-Host

}

&$script args0.txt args1.txt


NameString__DateString__Placestring

答案 1 :(得分:1)

param($data,$template)

Import-Csv -LiteralPath $data -Delimiter "`t" -Header Name,Date,Place | %{
    (sls "<NAME>" $template).Line -replace "<NAME>",$_.Name
    (sls "<DATE>" $template).Line -replace "<DATE>",$_.Date
    (sls "<PLACE>" $template).Line -replace "<PLACE>",$_.Place
}