bash – 在文件中第一次出现特定字符串之前删除所有行

前端之家收集整理的这篇文章主要介绍了bash – 在文件中第一次出现特定字符串之前删除所有行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
基本上我有一个像这样的文件
  1. junk
  2. morejunk
  3. somestring
  4. bats
  5. car
  6. somestring
  7. bats
  8. car
  9. somestring
  10. bats
  11. car

我想在第一次出现somestring之前删除所有垃圾,以便文件看起来像

  1. somestring
  2. bats
  3. car
  4. somestring
  5. bats
  6. car
  7. somestring
  8. bats
  9. car

我按照this question的建议使用sed -i’0,/ somestring /,d’file.txt,但是当我想将该行保留为第一行时,它会删除第一次出现somestring的行.

使用sed你可以使用:
  1. sed -i '/somestring/,$!d' file

替换表达式的说明:

, matches lines starting from where the first
address matches,and continues until the second match
(inclusively).

$ matches the last line of the last file of input,
or the last line of each file when the -i or -s options are
specified.

! If the character follows an address range,then only lines
which do not match the address range will be selected.

d Delete the pattern space; immediately start next cycle.

结果:

  1. $sed -i '/somestring/,$!d' file
  2. somestring
  3. bats
  4. car
  5. somestring
  6. bats
  7. car
  8. somestring
  9. bats
  10. car

猜你在找的Bash相关文章