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?
4 Answers
read can do the splitting itself, e.g.
read first last < name.txt
echo "$first"
echo "$last"
1 Comment
set - $variable; first=$1; last=$2Expanding 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
Comments
$first=`echo $line | sed -e 's/([^ ])+([^ ])+/\1/'`
$last=`echo $line | sed -e 's/([^ ])+([^ ])+/\2/'`