我有一个包含以数字开头的行的文件,例如
1 This is the first line
2 this is the second line
3 this is the third line
4 This is the fourth line
我想要做的是删除一行例如第2行并更新编号,以便文件如下所示,我想在bash脚本中执行此操作。
1 This is the first line
2 this is the third line
3 This is the fourth line
由于
答案 0 :(得分:5)
使用awk
IMO可能会更容易一些:
awk '!/regex/ {$1=++x; print}' inputFile
在/.../
中,您可以将regex
放在需要删除的行上。
$ cat inputFile
1 This is the first line
2 this is the second line
3 this is the third line
4 This is the fourth line
$ awk '!/second/ {$1=++x; print}' inputFile
1 This is the first line
2 this is the third line
3 This is the fourth line
$ awk '!/third/ {$1=++x; print}' inputFile
1 This is the first line
2 this is the second line
3 This is the fourth line
$ awk '!/first/ {$1=++x; print}' inputFile
1 this is the second line
2 this is the third line
3 This is the fourth line
注意:由于我们正在重新构建$1
字段,因此将删除任何空格序列。
答案 1 :(得分:1)
您可以使用以下命令集:
grep -v '^2 ' file | cut -d' ' -f2- | nl -w1 -s' '
grep
和-v
选项可以删除第2行。cut
程序会删除第一列,即行号。nl
。