dixits
1
Hi Guys,
I need to grep a specific string between a pattern. I have used sed command in the past in the following fashion:
set x = ROI_2_AND_mod_AND_name
echo $x | sed 's/.*ROI_\(.*\)_AND.*/\1/'
Returns:
2_AND_mod
I want:
2
But I want just the number "2". All I want is anything between "ROI_ and "_AND" (That is the first AND it sees). Can anybody help?
Thanks in advance.
I don't know if sed supports a non-greedy quantifier, but if Perl is an option, then:
$
$ echo $x
ROI_2_AND_mod_AND_name
$
$ echo $x | perl -plne 's/.*ROI_(.*?)_AND.*/$1/'
2
$
$
Alternatively, if the characters between "ROI_" and "_AND" always comprise of digit(s), then you could take advantage of that in your sed command.
vbe
3
or awk...
echo $x|awk -F\_ '/ROI_/ {print $2}'
test:
ant2:/regies/test $ echo $look4
ROI_2_AND_mod_AND_name
ant2:/regies/test $ echo $look4|awk -F\_ '/ROI_/ {print $2}'
2
echo $x
ROI_2_AND_mod_AND_name
echo $x | sed 's|^ROI_\(.*\)_AND_mod_.*|\1|'
2
rdrtx1
5
try also:
IFS=_ ; set -A ARR $(echo ROI_2_AND_mod_AND_name) ; echo ${ARR[1]}
echo $x | sed 's/.*ROI_\([^_]\).*/\1/'
--ahamed
dixits
7
---------- Post updated at 10:50 AM ---------- Previous update was at 10:49 AM ----------
---------- Post updated at 10:54 AM ---------- Previous update was at 10:50 AM ----------
Will it be only numbers and _? Try this...
echo $x | sed 's/.*ROI_\([0-9][0-9_]*\)_.*/\1/'
--ahamed
1 Like
This one will return nothing if there is no match
sed -n 's/.*ROI_\(.*\)_AND_mod.*/\1/p'
If the _mod
is not a constant one must use a restriction on the matching part in brackets:
sed -n 's/.*ROI_\([0-9][0-9_]*\)_AND.*/\1/p'
1 Like