如何从文件中删除行直到特定模式?

Kev*_*vin 4 command-line text-processing

我需要在文件中查找特定匹配项的行号 - 电子邮件地址 - 然后从文件的开头删除它,直到匹配的行。

例如,假设行号是13807。所以我需要保持13808+行完好无损。

下面是一个例子:

$ cat input
some
lines
before
mail@server.com
and
some
more
afterwards

$ cat output
and
some
more
afterwards
Run Code Online (Sandbox Code Playgroud)

des*_*ert 11

sed

sed '1,/mail@server\.com/d'  # excluding the matched line
sed '/mail@server\.com/,$!d' # including the matched line
Run Code Online (Sandbox Code Playgroud)

说明

  • 1,/mail@server\.com/dd删除从 line1到 ( ,) 的每一行mail@server.com
  • /mail@server\.com/,$!d– 不要 ( !)d删除从mail@server.com到 ( ,) 文件末尾( ) 的每一行$,但其他所有内容

用法

sed '…' file > file2 # save output in file2
sed -i.bak '…' file  # alter file in-place saving a backup as file.bak
sed -i '…' file      # alter file in-place without backup (caution!)
Run Code Online (Sandbox Code Playgroud)

awk

awk 'f;/mail@server\.com/{f=1}' # excluding the matched line
awk '/mail@server\.com/{f=1}f'  # including the matched line
Run Code Online (Sandbox Code Playgroud)

说明

  • f– variable f,默认情况下变量是0= falseawk如果表达式是,则不打印任何内容,如果表达式是false,则仅打印行true
  • /mail@server\.com/{f=1}– if mail@server.comis found set f=1,因此true在下一次f在表达式中呈现整个表达式

用法

awk '…' file > file2                          # save output in file2
awk -iinplace -vINPLACE_SUFFIX=.bak '…' file  # alter file in-place saving a backup as file.bak
awk -iinplace '…' file                        # alter file in-place without backup (caution!)
Run Code Online (Sandbox Code Playgroud)