SURESH0518
asked on
PowerShell
I have a text file which have two columns id,name as below
id|name
1|Test1
2|Test2
3|Test3
I want output as
id=1,name=Test1
id=2,name=Test2
id=3,name=Test3
How will I do in Windows PowerShell script. Any help is appreciated.
id|name
1|Test1
2|Test2
3|Test3
I want output as
id=1,name=Test1
id=2,name=Test2
id=3,name=Test3
How will I do in Windows PowerShell script. Any help is appreciated.
ASKER
Is there any way can I get column heading ID,name automatically without hard code. Sometimes I have two columns and sometimes I have 3 or more columns and I may not know column name upfront.
Example:
I may have
id|name|description
1|test|test1
2|test2|Test3
Sometime I may have
id|name|description|fundna me
1|test|Test1|XXX
2|test2|Test3|YYY
Example:
I may have
id|name|description
1|test|test1
2|test2|Test3
Sometime I may have
id|name|description|fundna
1|test|Test1|XXX
2|test2|Test3|YYY
Which code you trying? first one or second?
ASKER
Second one
Somewhat clumsy, but working:
Save it as whatever.ps1 and run it as whatever.ps1 <original_file> <target_copy> <number_of_columns>
Param (
[string]$originalName = "\path\to\file"
[string]$copyName = "\path\to\copy"
[Int32]$noColumns = 2
)
$arrHeader = @()
$header = (Get-Content $originalName -TotalCount 1).Split("|")
for ($i=0; $i -lt $noColumns; $i++) {
$arrHeader += $header[$i]
}
$text = ""
foreach ($line in get-content $originalName) {
$list = $line.Split("|")
for ($i=0; $i -lt $noColumns; $i++) {
$text = $text + $arrHeader[$i] + "=" + $list[$i] + ","
}
$text = $text.Substring(0, $text.Length - 1)
$text = $text + "`n"
}
echo $text > $copyName
Save it as whatever.ps1 and run it as whatever.ps1 <original_file> <target_copy> <number_of_columns>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
You are genius and thanks for quick solution and you are really great.
Open in new window
But if you want exactly same as you written then try..
Open in new window