在shell脚本中搜索多行,包括空白行 [英] Searching for multiple lines including a blank one in shell script

查看:85
本文介绍了在shell脚本中搜索多行,包括空白行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下命令查找跨越多行的模式并将其替换为空行:

I am using the following command to find a pattern spanning multiple lines and replacing it with a blank line:

sed -n '1h;1!H;${克;s/<模式1>\n<模式2>//g p }' <文件名>

比如找模式约翰能源部

在包含以下条目的文件 test.txt 中:

in a file test.txt which contains the following entries:

Mary

John
Doe
Simon
Henry

我会使用命令:

sed -n  '1h; 1!H; ${ g; s/John\nDoe //g p }' test.txt

但是,我似乎无法使此命令适用于第二行为空白的模式,即使用 ^$ 字符.

However, I can't seem to make this command work for a pattern which has the second line as a blank, i.e. using the ^$ character.

因此,如果我要搜索多行模式 Mary 后跟一个空行,我看不到任何匹配的模式.因此,以下命令不会导致搜索和替换.

Thus, if I were to search for the multi-line pattern, Mary followed by a blank line, I do not see any matching patterns. Thus, the following command causes no searches and thus no substitutions.

sed -n  '1h; 1!H; ${ g; s/Mary\n^$ //g p }' test.txt

有什么想法吗?

编辑

但是,如果我在一个文件中存储多个这样的命令并执行它们,那么第一次搜索会顺利进行,但是在搜索后续模式时,我会从 sed 得到一个空白输出.

However, if I store multiple such command in a file and execute them, then the first search goes through fine, however on searching for subsequent patterns, I get a blank output from sed.

也就是如果我存储,sed -n '1h;1!H;${克;s/\n//g p }' sed -n '1h;1!H;${克;s/\n//gp }' 在一个文件中,然后使用 eval 关键字执行此文件中的每一行,然后第一个 sed 替换第一个多行模式,即 pattern1,然后是 pattern2,但是,它返回一个空白输出,即使文件包含这些模式.有什么线索吗?

That is if I store, sed -n '1h; 1!H; ${ g; s/\n //g p }' sed -n '1h; 1!H; ${ g; s/\n //g p }' in a file and then execute each line in the this file using the eval keyword, then the first sed replaces the first multi-line patterns, i.e. pattern1, followed by pattern2, however, it returns a blank output even though the file contains these patterns. Any clues?

推荐答案

这对我来说适用于你的输入文件:

This works for me with your input file:

sed -n  '1h; 1!H; ${ g; s/Mary\n\n/\n/g p }'

说明:

Mary\n\n                # Mary with two consecutive newlines, the first one is automatically added by
                        # the 'H' command, and the next one means the empty line, asumming it has no
                        # spaces.
\n                      # Substitute it with a blank line.

这篇关于在shell脚本中搜索多行,包括空白行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆