Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

bash - sed - regex square brackets detection in Linux

I am using Ubuntu 14.04, and I have the following statement:

192.168.2.4 [text to capture] Test: This is a test statement.

I am trying to capture "text to capture" using the following regex:

echo "192.168.2.4 [text to capture] Test: This is a test statement" | sed -r "s/^[^[]]*[(.*)].*$/1/"

The idea behind the regex is to traverse over all characters which do not match opening and closing square bracket. Once an opening square bracket is encountered, capture the text until the closing bracket is encountered, then ignore all subsequent characters.

When I use the regex above in a regex tester, I can see that the "text to capture" is being captured.

However, executing the regex command above returns the complete statement aka:

echo "192.168.2.4 [text to capture] Test: This is a test statement" | sed -r "s/^[^[]]*[(.*)].*$/1/"

Can anyone spot what I have missed here? I believe I have escaped the characters brackets correctly, since it is working correctly with the regex tester.

Thanks John

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use this sed:

echo "192.168.2.4 [text to capture] Test: This is a test statement" |
sed -r 's/^[^[]*[([^]]*)].*$/1/'

text to capture

However for the sake of simplicity I suggest using awk to avoid complex regex:

echo "192.168.2.4 [text to capture] Test: This is a test statement" |
awk -F '[][]' '{print $2}'

text to capture

Here is a gnu grep alternative for the same (though awk is recommended):

echo "192.168.2.4 [text to capture] Test: This is a test statement" |
grep -oP '[^][]+(?=])'

text to capture

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...