我有一个看起来像这样的文件(伪代码):
---
foo: bar
bar: baz
---
baz: quz
---
Some text
Some text
Some text
我只需要删除第二 ---
行。我知道sed
可以做到这一点,但是我从来没有能够sed
找到我能找到的任何文件的头绪...
使用sed时,最简单的方法是首先将整个文件读入模式空间并进行处理:
sed ':a $!{N; ba}; s/\(^\|\n\)---\n/\n/2' filename
这确实
:a # jump label for looping
$!{ # if the end of input is not reached
N # fetch the next line, append it to the pattern space
ba # go back to :a
} # after this, the whole file is in the pattern space.
s/\(^\|\n\)---\n/\n/2 # then: remove the second occurrence of a line that
# consists only of ---
@ mklement0指出,\|
仅适用于GNU sed。解决该问题的一种方法是,由于\|
仅需抓住---
第一行,
sed ':a $!{ N; ba; }; s/^/\n/; s/\n---\n/\n/2; s/^\n//' filename
这样做:
:a $!{ N; ba; } # read file into the pattern space
s/^/\n/ # insert a newline before the first line
s/\n---\n/\n/2 # replace the second occurrence of \n---\n with \n
s/\n// # remove the newline we put in at the beginning.
这样,第一行不再是特例。
无需将整个文件读入缓冲区,就必须从字符构造一个计数器:
sed '/^---$/ { x; s/.*/&_/; /^__$/ { x; d; }; x; }' filename
那是:
/^---$/ { # if a line is ---
x # exchange pattern space and hold buffer
s/.*/&_/ # append a _ to what was the hold buffer
/^__$/ { # if there are exactly two in them
x # swap back
d # delete the line
}
x # otherwise just swap back.
}
...或只是使用awk:
awk '!/^---$/ || ++ctr != 2' filename
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句