Find string while knowing part of it and return string
If your grep
supports perl compatible regular expressions, you could match non-greedily up to the next word boundary:
echo "$string" | grep -oP 'Icecream.*?\b'
Otherwise, match the longest sequence of non-blank characters:
echo "$string" | grep -o 'Icecream[^[:blank:]]*'
Or keep everything in the shell and remove the longest trailing sequence of characters starting with a space:
echo "${string%% *}"
Since you tagged bash:
[[ $string =~ (Icecream[^ ]*) ]] && result=${BASH_REMATCH[1]}
More generally, for a search term in $search
:
[[ $string =~ ($search[^ ]*) ]] && result=${BASH_REMATCH[1]}
... or with parameter expansion:
# remove any leading text up to -and through- the search text:
x=${string##*$search}
# remove any trailing space onwards
result=$search${x%% *}
Using a grep
that knows about -o
:
$ printf '%s\n' "$string" | grep -o '\<Icecream[^[:blank:]]*'
Icecream123
The pattern \<Icecream[^[:blank:]]*
matches the string Icecream
(where the I
is preceded by a non-word character, or the start of the line) followed by zero or more non-blanks (not spaces or tabs).
Using awk
:
$ printf '%s\n' "$string" | awk -v RS=' ' '/^Icecream/'
Icecream123
The awk
program divides the string into space-separated records, and tests each one. It will print the ones that start with the string Icecream
.
Using mawk
or GNU awk
, you may also use
printf '%s\n' "$string" | awk -v RS='[[:blank:]]' '/^Icecream/'
since they interpet RS
as a regular expression if it contains more than one character.
With sed
, in a similar fashion as with grep
:
$ printf '%s\n' "$string" | sed 's/.*\(\<Icecream[^[:blank:]]*\).*/\1/'
Icecream123
Using /bin/sh
:
set -- Icecream123 AirplaneBCD CompanyTL1 ComputerYU1
for string; do
case $string in
Icecream*)
printf '%s\n' "$string"
break
esac
done
Perl (with a little help from tr
):
$ printf '%s\n' "$string" | tr ' ' '\n' | perl -ne '/Icecream\S*/ && print'
Icecream123
or just
$ printf '%s\n' "$string" | perl -ne '/(Icecream\S*)/ && print $1, "\n"'
Icecream123