sed - 只从多行输入中获取替换的字符串并省略不匹配的行!

por*_*org 18 regex replace sed multiline

我希望 sed省略所有不匹配的行,并且只输出替换的字符串(单个/多个预期行/ s).

换句话说:我有一个干草堆,只想要针回来,而不是所有被搜查的干草,并且保持不变.

或者换句话说:在多行字符串中搜索/替换RegEx描述的字符串,并且只返回该字符串.(因为可以使用PHP函数http://www.php.net/manual/en/function.preg-replace.php)

我目前的解决方法是首先使用grep进行过滤,然后仅将匹配的行传输到sed中进行替换:

echo -e "Bla\nBla\nImportant1: One \nBla\nImportant2: Two\nBla\nBla" | egrep "^Important1.*$" | sed -E "s/^Important1: *\b(.*)\b */\1/g"
# From the multiple line input I only want the "One One" (with pre/post whitespace removed, hence matching the word boundaries with "\b")
# And I want no "Bla bla" lines in the result!
Run Code Online (Sandbox Code Playgroud)

但我想在sed中有一个单一的解决方案.或者这是出于预期的sed用法,我应该更好地使用其他东西吗?顺便说一句,问题:使用反向引用的多线sed似乎有点相关,但我不确定!

anu*_*ava 13

编辑:以下在Mac和Linux上进行了测试.

你可以像这样使用sed:

echo -e "Bla\nBla\nImportant1: One \nBla\nImportant2: Two\nBla\nBla" | \
   sed -n 's/^Important1: *\([^ ]*\) */\1/p'

OUTPUT:
one
Run Code Online (Sandbox Code Playgroud)

说明

sed -n 's/^Important1: *\([^ ]*\) */\1/p'

-n # quiet / silent 

{
  s/^Important1: *\([^\ ]*\) */\1/ # replace "Important1: one " with 1st group i.e. "one"
  p                  # print the replaced text
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*rau 6

这个sed命令执行你的egrep和sed的组合:

echo -e "Bla\nBla\nImportant1: One \nBla\nImportant2: Two\nBla\nBla"
| sed -n -e "s/^Important1: *\b\(.*\)\b */\1/p"
Run Code Online (Sandbox Code Playgroud)

您执行替换并仅在替换后打印匹配的行.


Sie*_*geX 5

sed -n '/^Important1.*$/s/^Important1: *\b\(.*\)\b */\1/p'
Run Code Online (Sandbox Code Playgroud)

概念证明

$ echo -e "Bla\nBla\nImportant1: One \nBla\nImportant2: Two\nBla\nBla" | sed -n '/^Important1.*$/s/^Important1: *\b\(.*\)\b */\1/p'
One
Run Code Online (Sandbox Code Playgroud)