删除行和更新订单

时间:2013-06-12 02:08:34

标签: bash

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

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

由于

2 个答案:

答案 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' '
  1. 使用grep-v选项可以删除第2行。
  2. cut程序会删除第一列,即行号。
  3. 最后,我们只需对行进行重新编号,以便我们使用nl