Reputation: 155
How can we fetch a substring from a string in bash using scripting language?
Example:
fullstring="mnuLOCNMOD.URL = javascript:parent.doC...something"
The substring I want is everything before ".URL" in the full string.
Upvotes: 1
Views: 89
Reputation: 440677
To offer yet another alternative: Bash's regular-expression matching operator, =~
:
fullstring="mnuLOCNMOD.URL = javascript:parent.doC...something"
echo "$([[ $fullstring =~ ^(.*)'.URL' ]] && echo "${BASH_REMATCH[1]}")"
Note how the (one and only) capture group ((.*)
) is reported through element 1
of the special "${BASH_REMATCH[@]}"
array variable.
While in this case l3x's parameter expansion solution is simpler, =~
generally offers more flexibility.
awk
offers an easy solution as well:
echo "$(awk -F'\\.URL' '{ print $1 }' <<<"$fullstring")"
Upvotes: 0
Reputation: 155
fullstring="mnuLOCNMOD.URL = javascript:parent.doC...something"
menuID=`echo $fullstring | cut -f 1 -d '.'`
here I used dot as a separator this works in .sh files
Upvotes: 0
Reputation: 42147
Parameter Expansion is the way to go.
If you are interested in a simple grep
:
% fullstring="mnuLOCNMOD.URL = javascript:parent.doC...something"
% grep -o '^[^.]*' <<<"$fullstring"
mnuLOCNMOD
Upvotes: 0
Reputation: 121427
With Parameter Expansion, you can do:
fullstring="mnuLOCNMOD.URL = javascript:parent.doC...something"
echo ${fullstring%\.URL*}
prints:
mnuLOCNMOD
Upvotes: 5
Reputation: 96016
You can use grep
:
echo "mnuLOCNMOD.URL = javas" | grep -oP '\w+(?=\.URL)'
and assign the result to a string. I used a positive lookahead (?=regex
) because it's a zero length assertion, meaning that it'll be matched but won't be displayed.
Run grep --help
to find out what o
and P
flags stand for.
Upvotes: 0
Reputation: 8769
$ fullstring="mnuLOCNMOD.URL = javascript:parent.doC...something"
$ sed -r 's/^(.*)\.URL.*$/\1/g' <<< "$fullstring"
mnuLOCNMOD
$
Upvotes: 1