Reputation: 119
sapmple.txt as below
row1col1||col2||col2||col3
row2col1||col2||col2||col3
row3col1||col2||col2||col3
expected
0||row1col1||col2||col2||col3
1||row2col1||col2||col2||col3
2||row3col1||col2||col2||col3
I coded like
get-content "C:\sample.txt" | foreach { "[|][|]" + $_ } | foreach { Index + $_ } | set-content "C:\sample1.txt"
calling the pipe and then respective index, but not working.
Can you please help.
Upvotes: 4
Views: 4226
Reputation: 46710
What is index
in your example? Strings do not have an index property nor does Get-Content
create one as far as I know.
Get-Content
already knows line numbers using ReadCount
so keeping a running index is redundant. It does however start counting at one so a small adjustment would need to be made there to match your desire.
Get-Content C:\temp\text.txt | ForEach-Object {"{0}||{1}" -f ($_.ReadCount - 1),$_}
We use the format operator -f
to try and make for easier to edit output string. Simply pipe the output of the foreach-object
to its desired output.
Upvotes: 1
Reputation: 61093
just like this:
$index = 0
Get-Content 'C:\sample.txt' | ForEach-Object { "{0}||{1}" -f $index++, $_ } | Set-Content 'C:\sample1.txt'
If want to prepend leading zeroes to your index so also larger numbers will align (in this example all indices will have 4 digits):
Get-Content 'C:\sample.txt' | ForEach-Object { "{0}||{1}" -f ($index++).ToString("0000") , $_ } | Set-Content 'C:\sample1.txt'
Upvotes: 3