Reputation: 1862
Suppose I have a string variable in a bash script that contained several lines:
blah blah blah
...
...
an interesting parameter: 12345 some other useless stuff...
...
...
I want to extract 12345 from this string. I have tried to look for ways to use 'an interesting parameter:' as a "delimeter" but I couldn't quite get it to work. Is there a clean way of doing this?
Upvotes: 4
Views: 4300
Reputation: 174766
Try this sed
command,
sed -n '/interesting parameter/ s/.*parameter: \([0-9]\+\) .*/\1/p' file
For your case it would be,
sed -n '/interesting parameter/ s/.*parameter: \([0-9]\+\) .*/\1/p' <<< "$string"
Upvotes: 3
Reputation: 46843
Pure Bash using regex:
$ a='blah blah blah
> ...
> ...
> an interesting parameter: 12345 some other useless stuff...
> ...
> ...'
$ [[ $a =~ "an interesting parameter: "([[:digit:]]+) ]] && echo "${BASH_REMATCH[1]}"
12345
Pure Bash using parameter expansions:
$ t=${a#*an interesting parameter: }
$ echo "$t"
12345 some other useless stuff...
...
...
$ u=${t%% *}
$ echo "$u"
12345
Upvotes: 3
Reputation: 531718
bash
supports regular expression matching without using external programs.
$ str='
blah blah blah
...
...
an interesting parameter: 12345 some other useless stuff...
...
...'
$ [[ $str =~ an\ interesting\ parameter:\ ([[:digit:]]+) ]]
$ echo ${BASH_REMATCH[1]}
12345
The array BASH_REMATCH
contains the full match in element 0 and the captured subgroups (in left-to-right order) in subsequent elements.
Upvotes: 5
Reputation: 5470
Try this:
cat content | grep "an interesting parameter: " | awk '{print $4}'
Upvotes: 1
Reputation: 158080
You can use sed:
sed -n 's/.*an interesting parameter: \([0-9]\+\).*/\1/p' <<< "$string"
Upvotes: 3