0

我有一个文件,其中包含以数字开头的行,例如

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

谢谢

4

2 回答 2

5

IMO 可能会更容易一些awk

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字段,任何空白序列都将被删除。

于 2013-06-12T02:12:35.397 回答
1

您可以使用这组命令:

grep -v '^2 ' file | cut -d' ' -f2- | nl -w1 -s' '
  1. 使用grepwith-v选项可以删除第 2 行。
  2. cut程序剪切第一列,即行号。
  3. 最后,我们只需要重新编号行,所以我们使用nl.
于 2013-06-12T02:15:09.467 回答