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
您的循环将处理整个文件
Numlines
时间,无论如何都将后缀添加到每一行。此外,您的循环变量是在 sed 命令中$line
使用$i
的,并且在大多数 shell 中,您的分配在Numlines
语法上是不正确的。你可以做
请注意,作业喜欢
Numlines=$(wc -l < file.txt)
或您原来的(它可能没有)在
=
in bash 和类似的 shell 周围不能有空格。然而,使用 shell 循环以这种方式处理文件效率低下 - 恕我直言,在 awk 中使用类似以下内容会更好:
或在 perl 中或多或少等效:
如果 sed 是您唯一可用的工具,那么您可以使用它两次 - 一次使用
=
命令对行编号,然后第二次格式化结果: