Jonathan
Jonathan

Reputation: 2845

Extract first word of string in bash using regular expressions

I have a string like "abc def". Using Bash and regular expressions I want to set a Bash variable to the value of the first word. I have tried the following code:

testVar="abc def"
re="^[[:space]]([a-zA-z0-9)[[[:space]]|$]"
sub=[[ "$testVar" ~= ${re} ]]; ${BASH_REMATCH[0]}
echo "${sub}"

This gives me the response "./test1.sh: line 3: abc def: command not found". Any suggestions on what I am doing wrong?

Upvotes: 0

Views: 2236

Answers (3)

Sudosu0
Sudosu0

Reputation: 157

If your string isn't space delimited. You can use sed to split the string into a new line for each delimiter, and use head to select only the first row.

$ testVar="abc,def,ghi"
$ echo $testVar | sed 's/,/\n/g' | head -n 1
abc

Upvotes: 1

James Brown
James Brown

Reputation: 37404

Another:

$ echo ${testVar%% *}
abc

More here: https://www.tldp.org/LDP/abs/html/parameter-substitution.html

Upvotes: 2

anubhava
anubhava

Reputation: 785146

Here is a simple solution using read:

testVar="abc def"
read word _ <<< "$testVar"
echo "$word"

abc

If you really want to use a regex then use:

re='[^[:blank:]]+'
[[ $testVar =~ $re ]] && echo "${BASH_REMATCH[0]}"

abc

Here [^[:blank:]]+ matches 1 or more of any non-whitespace characters.

Upvotes: 3

Related Questions