1

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
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
user2330632
  • 15
  • 1
  • 5

2 Answers2

6

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Incidentally, one advantage of this technique is that if the name is `Jim Kennedy` instead of just `Jim`, this gets the correct value into `$name`. The other answers will have problems with `Kennedy` being the date, `02DEC99` being the number, and `2 3` being the age. – Jonathan Leffler Apr 29 '13 at 07:34
  • Intrigued by your excellent -n 2p sed modifier but unable to find it in the documentation. Found this explaination: http://stackoverflow.com/a/1429628/1207958 – svante Apr 29 '13 at 07:59
  • 1
    @svante: I'm practicing DRY — Don't Repeat Yourself. :D I'll add some comments to explain the `sed` command. – Jonathan Leffler Apr 29 '13 at 12:52
0

You can use this:

read name date number age <<< $(awk -F: 'NR==2{printf("%s %s %s %s\n", $1, $2, $3, $4)}' inFile)

echo "$name"
echo "$date"
echo "$number"
echo "$age"
anubhava
  • 761,203
  • 64
  • 569
  • 643