Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse multiline file and do some operation for each token line in bash?

Tags:

bash

csv

tsv

say we have a tsv file

1    2    3
1    2    3

we want to do some operation say echo $1 $2 $3 for each tsv file line.

How to do such thing in bash?

like image 894
DuckQueen Avatar asked Jun 14 '13 10:06

DuckQueen


1 Answers

This can make it:

while read -r a b c
do
   echo "first = $a second = $b third = $c"
done < file

Test

$ while read -r a b c; do echo "first=$a second=$b third=$c"; done < file
first=1 second=2 third=3
first=1 second=2 third=3

As the separator is a tab, you don't need to use IFS. If it was for example a |, you could do:

$ cat file
1|2|3
1|2|3
$ while IFS='|' read -r a b c; do echo "first=$a second=$b third=$c"; done < file
first=1 second=2 third=3
first=1 second=2 third=3
like image 136
fedorqui 'SO stop harming' Avatar answered Oct 22 '22 22:10

fedorqui 'SO stop harming'