Home > bash > bash – working with spaces

bash – working with spaces

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
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: