![如何为文件的每一行添加交互值?](https://linux22.com/image/930694/%E5%A6%82%E4%BD%95%E4%B8%BA%E6%96%87%E4%BB%B6%E7%9A%84%E6%AF%8F%E4%B8%80%E8%A1%8C%E6%B7%BB%E5%8A%A0%E4%BA%A4%E4%BA%92%E5%80%BC%EF%BC%9F.png)
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/'