我想sed忽略所有不匹配的行,而只输出(单个/多个预期行的)替换字符串。
换句话说:我有一个干草堆,只希望返回针头,而不是所有被搜索到并保持不变的干草。
或换句话说:在多行字符串中搜索/替换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!
但是我想在sed中有一个解决方案。还是这超出了预期的sed用法,因此我应该更好地使用其他东西吗?顺便说一句,问题:multiline sed using backreferences似乎有某种联系,但我不确定!
最佳答案
编辑:以下已在Mac和Linux上进行了测试。
您可以像这样使用sed:
echo -e "Bla\nBla\nImportant1: One \nBla\nImportant2: Two\nBla\nBla" | \
sed -n 's/^Important1: *\([^ ]*\) */\1/p'
OUTPUT:
one
说明
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
}
关于regex - sed-从多行输入中仅获取替换的字符串,并忽略不匹配的行!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5544322/