2

When we have file which is a kind of list like :

Mary 34
George 45
John 56
Josh 29

using the awk command $1 refers to the first column and $2 to the second column.But once we write a shell script we can use the read line to read the whole line or we can use read number to read the first word,am I right?So my question is in the above if I wanted to read the second column how would I do that without using awk command from a shell-script.

3 Answers 3

6
while read firstcol secondcolandtherest ;
do
    something
done < the_file

ie: when you put several arguments to "read", it puts the first one in the first arg, the 2nd one in the 2nd arg, etc. In the last arg it put the "rest of the line".

some examples:

#if you want to read line by line: only 1 arg (therefore, it puts everyuthing in it, as the only arg is the last arg)
while read whole_line ; 
do
     something with "$whole_line"
done

#if you only want only column 1 in $first, and everything else in $second_and_rest_of_line:
while read  first second_and_rest_of_line
 do
     something with "$first" and "$second_and_rest_of_line"
done

#if you only want col 1 and 2, and don't care about any extra cols:
while read  first  second  nonimportant
do
     something with $first and "$second" #and we don't care about $nonimportant's content
done

Please note that: you should really add "-r" (to get raw input) option to read, and modify the IFS according to what you need... But the above examples are for discussing the "arguments", not the proper read invocation. See http://mywiki.wooledge.org/BashPitfalls for info about this and many other subtleties

1
  • 1
    you should really add "-r" (to get raw input) option to read, and modify the IFS according to what you need... But the above examples are for discussing the "arguments", not the proper read invocation Commented Dec 10, 2013 at 15:06
1
while read -a line; do echo -e "${line[1]}"; done < file
34
45
56
29

where file contains your list.

0

In bash:

$ read -a arr <<< 'Mary 34'
$ echo "${arr[1]}"
34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .