Syngularity
Syngularity

Reputation: 824

Bash script rewrite in powershell

I have a bash script that put names, dates, and place in to a sample file. The code looks like this

#/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

I want to write it in powershel. This is my try:

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"}

}

But it's dosent work, but i dont know why :S

Upvotes: 2

Views: 508

Answers (2)

user2521845
user2521845

Reputation: 41

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
}

Upvotes: 1

mjolinor
mjolinor

Reputation: 68341

The obvious problem is an apparent typo here:

$samplpe = Get-Content $args[0]

Beyond that, it's hard to tell without knowing what the data looks like, but it appears to be much more complicated than it needs to be. I'd do something like this (best guess on what the data looks like).

'<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

Upvotes: 1

Related Questions