剪切匹配行和X连续线,直到newline并将其粘贴到文件中



我想匹配包含一个单词的文件的所有行,并将所有行键入下面,直到连续出现两个两个新线字符。

我有以下剪切和粘贴特定行的SED代码,但不随后的行:

sed 's|.*|/\<&\>/{w resultsnd}|' teststring | sed -file.bak -f - testfile

如何修改此操作以采用所有后续行?

例如,说我想与"狗"匹配,以下应为5:

的前3行。
The best kind of an animal is a dog, for sure
-man's best friend
-related to wolves
Racoons are not cute

有没有办法做到这一点?

这应该做:

awk '/dog/ {f=1} /^$/ {f=0} f {print > "new"} !f {print > "tmp"}' file && mv tmp file

如果找到Word dog,它将将f设置为true,则如果找到空白行将f设置为false。
如果f为TRUE,请打印到new文件。
如果f是错误的,请打印到tmp文件。
tmp文件复制到原始文件

编辑:可以缩短一些:

awk '/dog/ {f=1} /^$/ {f=0} {print > (f?"new":"tmp")}' file && mv tmp file

edit2:根据要求,添加new文件中每个部分的空间:

awk '/dog/ {f=1;print ""> "new"} /^$/ {f=0} {print > (f?"new":"tmp")}' file && mv tmp file

如果原始文件确实包含选项卡或空格,而不仅仅是每个狗部分之后的空白行,请从/^$/更改为/^[ t]*$/

这可能对您有用(gnu sed(:

sed 's|.*|/\<&\>/ba|' stringFile | 
sed -f - -e 'b;:a;w resultFile' -e 'n;/^$/!ba' file

从字符串文件中构建一组Regexps,并将匹配项发送到:a。然后将匹配的行和任何其他行写入结果。

n.b。结果可以直接发送到ResultFile,使用:

sed 's#.*#/\<&\>/ba#' stringFile |
sed -nf - -e 'b;:a;p;n;/^$/!ba' file > resultFile

剪切原始文件中的匹配:

sed 's|.*|/\<&\>/ba|' stringFile |
sed -f - -e 'b;:a;N;/ns*$/!ba;w resultFile' -e 's/.*//p;d' file

这是您要做的吗?

$ awk -v RS= '/dog/' file
The best kind of an animal is a dog, for sure
-man's best friend
-related to wolves

您可以尝试以下内容。

awk '/dog/{count="";found=1} found && ++count<4'  Input_file > temp && mv temp Input_file

最新更新