4

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 4

7

read can do the splitting itself, e.g.

read  first last < name.txt

echo "$first"
echo "$last"
Sign up to request clarification or add additional context in comments.

1 Comment

Or if you have them in a variable already, set - $variable; first=$1; last=$2
7

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

Comments

2

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.

Comments

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

1 Comment

hmm... looks like I need to re-read my unix tools book, it indeed doesn't work, I just wrote what's in my memory. sorry...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.