Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Say I have this file:

hello
world
hello world

This program

#!/bin/bash

for i in $(cat $1); do
    echo "tester: $i"
done

outputs

tester: hello
tester: world
tester: hello
tester: world

I'd like to have the for iterate over each line individually ignoring whitespaces though, i.e. the last two lines should be replaced by

tester: hello world

Using quotes for i in "$(cat $1)"; results in i being asigned the whole file at once. What should I change?

share|improve this question
add comment

1 Answer

up vote 22 down vote accepted

With for and IFS:

#!/bin/bash

IFS=$'\n'       # make newlines the only separator
set -f          # disable globbing
for i in $(cat "$1"); do
  echo "tester: $i"
done

Or with read (no more cat):

#!/bin/bash

while IFS= read -r line; do
  echo "tester: $line"
done < "$1"
share|improve this answer
2  
thanks, I didn't know one could < into a whole loop. Although it makes perfectly sense now I saw it –  Tobias Kienzler Feb 7 '11 at 11:06
1  
I see IFS \ read -r line' in second example. Is really IFS=` needed ? IMHO it enough to say : while read -r line; do echo "tester: $line"; done < "$1" –  Grzegorz Wierzowiecki Mar 19 '12 at 16:45
1  
@GrzegorzWierzowiecki IFS= turns off the stripping of leading and trailing whitespace. See In while IFS= read.., why does IFS have no effect? –  Gilles Jan 12 at 0:29
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.