如何为文件的每一行添加交互值?

如何为文件的每一行添加交互值?
Numlines=$(grep "" -c file.txt) # This works
for line in $( seq 1 $Numlines) # for each line 
do
sed "s/$/ Line${i}/" file.txt # not right
done

文件.txt:

this is the first line
this is the second line
this is the third line

期望输出

this is the first line  Line1
this is the second line  Line2
this is the third line  Line3

相反,我得到的是:

this is the first line Line1
this is the second line Line1
this is the third line Line1
this is the first line Line2
this is the second line Line2
this is the third line Line2
this is the first line Line3
this is the second line Line3
this is the third line Line3

答案1

您的循环将处理整个文件Numlines时间,无论如何都会将后缀添加到每一行。此外,您的循环变量是$line$i在 sed 命令中使用的,并且您的赋值Numlines在大多数 shell 中在语法上都是错误的。

可以

Numlines=$(wc -l < file.txt)
for i in $(seq 1 "$Numlines"); do sed -n "${i}s/$/ Line${i}/p" file.txt; done

请注意,像Numlines=$(wc -l < file.txt)或你的原始

Numlines = $(grep "" -c file.txt) # This works

(可能没有)=在 bash 和类似的 shell 中周围不能有空格。

但是使用 shell 循环来以这种方式处理文件效率低下 - 在我看来,最好在 awk 中使用类似下面的方法:

awk '{$(NF+1) = "Line" FNR} 1' file.txt

或者在 perl 中或多或少等效地:

perl -lpe '$_ .= " Line $."' file.txt

如果 sed 是您唯一可用的工具,那么您可以使用它两次 - 一次使用命令=对行进行编号,然后第二次格式化结果:

sed = file.txt | sed '$!N;s/\(.*\)\n\(.*\)/\2 Line\1/'

相关内容