[英]sed not working as expected (trying to get value between two matches in a string)
I have a file (/tmp/test) the has a the string "aaabbbccc" in it 我有一个文件(/ tmp / test),其中有一个字符串“ aaabbbccc”
I want to extract "bbb" from the string with sed. 我想用sed从字符串中提取“ bbb”。
Doing this returns the entire string: 这样做将返回整个字符串:
sed -n '/aaa/,/ccc/p' /tmp/test
I just want to return bbb from the string with sed (I am trying to learn sed so not interested in other solutions for this) 我只想用sed从字符串中返回bbb(我试图学习sed,所以对此不感兴趣。)
Sed works on a line basic, and a,b{action}
will run action for lines matching a
until lines matching b
. Sed在基本行上工作,并且
a,b{action}
将对与a
匹配a
行运行action,直到与b
匹配a
行。 In your case 就你而言
sed -n '/aaa/,/ccc/p'
will start printing lines when /aaa/
is matched, and stop when /ccc/
is matched which is not what you want. 将在
/aaa/
匹配时开始打印行,在/ccc/
匹配时停止打印行,这不是您想要的。
To manipulate a line there is multiply options, one is s/search/replace/
which can be utilized to remove the leading aaa
and trailing ccc
: 要操纵一行,有多个选项,其中一个是
s/search/replace/
,可以用来删除前导aaa
和尾随ccc
:
% sed 's/^aaa\|ccc$//g' /tmp/test
bbb
Breakdown: 分解:
s/
^aaa # Match literal aaa in beginning of string
\| # ... or ...
ccc$ # Match literal ccc at the end of the sting
// # Replace with nothing
g # Global (Do until there is no more matches, normally when a match is
# found and replacement is made this command stops replacing)
If you are not sure how many a
's and c
's you have you can use: 如果不确定要使用多少个
a
和c
,可以使用:
% sed 's/^aa*\|cc*$//g' /tmp/test
bbb
Which will match literal a
followed by zero or more a
's at the beginning of the line. 这将与字面量
a
匹配,后跟零或多个a
。 Same for the c
's but just at the end. 与
c
相同,但仅在末尾。
With GNU sed: 使用GNU sed:
sed 's/aaa\(.*\)ccc/\1/' /tmp/test
Output: 输出:
bbb
See: The Stack Overflow Regular Expressions FAQ 请参阅: 堆栈溢出正则表达式常见问题解答
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.