我需要在文件中查找特定匹配的行号 - 电子邮件地址 - 然后从文件开头删除它直到匹配的行。
例如假设行号是13807。所以我需要保留13808+ 线路完好。
以下是一个例子:
$ cat input
some
lines
before
[email protected]
and
some
more
afterwards
$ cat output
and
some
more
afterwards
答案1
#sed
sed '1,/mail@server\.com/d' # removing the matched line
sed '/mail@server\.com/,$!d' # keeping the matched line
###解释
1,/mail@server\.com/d
–删除从第到 ( )行的d
每一行1
,
[email protected]
/mail@server\.com/,$!d
– 不要 (!
)删除从到 ( ) 文件末尾 ( ) 的d
每一行,但删除其他所有内容[email protected]
,
$
###用法
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!)
#awk
awk 'f;/mail@server\.com/{f=1}' # excluding the matched line
awk '/mail@server\.com/{f=1}f' # including the matched line
###解释
f
– 变量f
,变量默认为0
= ,如果表达式为,则不打印任何内容,如果表达式为,则只打印该行false
awk
false
true
/mail@server\.com/{f=1}
– 如果[email protected]
发现集合,则下次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!)
答案2
另一种awk
方法,包括匹配的线。
awk '/pattern/, 0' infile
排除匹配的行。
awk '/pattern/&& getline, 0' infile