Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash while loop with read and IFS

I have to parse a file in the following format:

line1_param1:line1_param2:line1_param3:
line1_param2:line2_param2:line2_param3:
line1_param3:line3_param2:line3_param3:

And process it line by line, extracting all parameters from current line. Currently I've managed it in such a way:

IFS=":"
grep "nice" some_file | sort > tmp_file
while read param1 param2 param3
do
  ..code here..
done < tmp_file
unset IFS

How can I avoid a creation of a temporary file?

Unfortunately this doesn't work correctly:

IFS=":"
while read param1 param2 param3
do
  ..code here..
done <<< $(grep "nice" some_file | sort)
unset IFS

As the whole line is assigned to the param1.

like image 742
Dejwi Avatar asked Feb 13 '26 19:02

Dejwi


1 Answers

You can use process substitution for this:

while IFS=: read -r param1 param2 param3
do
   echo "Any code here to process: $param1 $param2 $param3"
done < <(grep "nice" some_file | sort)
like image 183
anubhava Avatar answered Feb 15 '26 11:02

anubhava