简体   繁体   English

如何在Powershell中的文件的每一行上打印/附加行索引号

[英]How to print/append row index number on each line in a file in Powershell

sapmple.txt as below sampple.txt 如下

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.你能帮忙吗。

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):如果想要在索引前加上前导零,那么更大的数字也会对齐(在本例中,所有索引都有 4 位数字):

Get-Content 'C:\sample.txt' | ForEach-Object { "{0}||{1}" -f ($index++).ToString("0000") , $_ } | Set-Content 'C:\sample1.txt'

What is index in your example?你的例子中的index是什么? Strings do not have an index property nor does Get-Content create one as far as I know.据我所知,字符串没有索引属性,也没有Get-Content创建一个。

Get-Content already knows line numbers using ReadCount so keeping a running index is redundant. Get-Content已经使用ReadCount知道行号,因此保持运行索引是多余的。 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.我们使用格式运算符-f来尝试使编辑输出字符串更容易。 Simply pipe the output of the foreach-object to its desired output.只需将foreach-object的输出通过管道foreach-object到其所需的输出。

另一个想法:

% { $i = 0 } { "$i||$_" ; $i++ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM