2

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.

user10118202
  • 89
  • 1
  • 4
  • Possible duplicate of [Get index of current item in Powershell loop?](https://stackoverflow.com/questions/1785474/get-index-of-current-item-in-powershell-loop) –  Jul 28 '18 at 18:46

3 Answers3

2

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'
Theo
  • 49,970
  • 8
  • 20
  • 38
1

Another thought:

% { $i = 0 } { "$i||$_" ; $i++ }
mklement0
  • 312,089
  • 56
  • 508
  • 622
Bob
  • 338
  • 3
  • 18
1

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.

Matt
  • 42,566
  • 8
  • 67
  • 104