Read words in a specific line in a text file using shell script

user2330632 picture user2330632 · Apr 29, 2013 · Viewed 8.9k times · Source

In my Bash shell script, I would like to read a specific line from a file; that is delimited by : and assign each section to a variable for processing later.

For example I want to read the words found on line 2. The text file:

abc:01APR91:1:50
Jim:02DEC99:2:3
banana:today:three:0

Once I have "read" line 2, I should be able to echo the values as something like this:

echo "$name";
echo "$date";
echo "$number";
echo "$age";

The output would be:

Jim
02DEC99
2
3

Answer

Jonathan Leffler picture Jonathan Leffler · Apr 29, 2013

For echoing a single line of a file, I quite like sed:

$ IFS=: read name date number age < <(sed -n 2p data)
$ echo $name
Jim
$ echo $date
02DEC99
$ echo $number
2
$ echo $age
3
$

This uses process substitution to get the output of sed to the read command. The sed command uses the -n option so it does not print each line (as it does by default); the 2p means 'when it is line 2, print the line'; data is simply the name of the file.