Reputation: 2413
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
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
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
Reputation: 17188
read can do the splitting itself, e.g.
read first last < name.txt
echo "$first"
echo "$last"
Upvotes: 7
Reputation: 9340
$first=`echo $line | sed -e 's/([^ ])+([^ ])+/\1/'`
$last=`echo $line | sed -e 's/([^ ])+([^ ])+/\2/'`
Upvotes: -1