waa1990
waa1990

Reputation: 2413

How do I take a string and split it into 2 variables in bash?

I have a string that is read in from a file in the format "firstname lastname". I want to split that string and put it into two separate variables $first and $last. What is the easiest way to do this?

Upvotes: 4

Views: 13236

Answers (4)

l0b0
l0b0

Reputation: 58808

Expanding on fgm's answer, whenever you have a string containing tokens separated by single characters which are not part of any of the tokens, and terminated by a newline character, you can use the internal field separator (IFS) and read to split it. Some examples:

echo 'John Doe' > name.txt
IFS=' ' read first last < name.txt
echo "$first"
John
echo "$last"
Doe

echo '+12 (0)12-345-678' > number.txt
IFS=' -()' read -a numbers < number.txt
for num in "${numbers[@]}"
do
    echo $num
done
+12
0
12
345
678

A typical mistake is to think that read < file is equivalent to cat file | read or echo contents | read, but this is not the case: The read command in a pipe is run in a separate subshell, so the values are lost once read completes. To fix this, you can either do all the operations with the variables in the same subshell:

echo 'John Doe' | { read first last; echo $first; echo $last; }
John
Doe

or if the text is stored in a variable, you can redirect it:

name='John Doe'
read first last <<< "$name"
echo $first
John
echo $last
Doe

Upvotes: 6

xvdd
xvdd

Reputation: 47

cut can split strings into parts separated by a chosen character :

first=$(echo $str | cut -d " " -f 1)
last=$(echo $str | cut -d " " -f 2)

It is probably not the most elegant way but it is certainly simple.

Upvotes: 2

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17188

read can do the splitting itself, e.g.

read  first last < name.txt

echo "$first"
echo "$last"

Upvotes: 7

LeleDumbo
LeleDumbo

Reputation: 9340

$first=`echo $line | sed -e 's/([^ ])+([^ ])+/\1/'`
$last=`echo $line | sed -e 's/([^ ])+([^ ])+/\2/'`

Upvotes: -1

Related Questions