using =~ operator to match output of a command and grab group from it. Code is as follows:
Comamndout=$(cmd) Match=‘^hello world’ If $Comamndout =~ $Match; then echo something fi
Commandout is in pattern Something Hello world
But if statement is failing. Is bash regex support multiline search with everyline start with ^ and end with $.
CodePudding user response:
No, the =~
operator doesn't perform a multiline search. A newline must be matched literally:
string=$(cmd)
regexp='(^|'$'\n'')hello world'
if [[ $string =~ $regexp ]]; then
echo matches
fi
CodePudding user response:
=~
would treat multiple lines as one line.
if [[ $(echo -e "abc\nd") =~ ^a.*d$ ]]; then
echo "find a string '$(echo -e "abc\nd")' that starts with a and ends with d"
fi
Output:
find a string 'abc
d' that starts with a and ends with d
P.S.
When processing multiple lines, it is common to use grep
or read
with either re-direct or pipeline.
For a
grep
and pipeline example:# to find a line start with either a or e echo -e "abc\nd\ne" | grep -E "^[ae]"
Output:
abc e
For a
read
and redirect example:while read line; do if [[ $line =~ ^a} ]] ; then echo "find a line '${line}' start with a" fi done <<< $(echo -e "abc\nd\ne")
Output:
find a line 'abc' start with a
P.S.
-e
of echo
means translate following \n
into new line. -E
of grep
means using the extended regular expression to match.