Archive

Posts Tagged ‘IFS. read’

bash – working with spaces

August 16, 2011 Leave a comment

Problem:
Have bash ignore the spaces between words when looping through a file.

Eg

shell> cat model_country.txt
Toyota / Japan
Subaru / Japan
Audi / Germany
shell>for list in $(cat model_country.txt);do echo $list; done
Toyota
/
Japan
Subaru
/
Japan
Audi
/
Germany
 

Solution:
1. Change IFS

shell>export IFS=$'\n'

shell>for list in $(cat model_country.txt);do echo $list; done
Toyota / Japan
Subaru / Japan
Audi / Germany

Source:
http://blog.ynema.com/?p=260

NB. No need to change IFS back to ‘ \t\n’ as changes made in the example above are lost once the terminal is closed.

2. Use read

shell>cat model_country.txt | while read list; do echo $list; done
Toyota / Japan
Subaru / Japan
Audi / Germany

Source:
http://sandrylogan.wordpress.com/2011/06/10/line-by-line-in-bash-coping-with-the-spaces/

Advertisements