Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

When I want to do something with each line in a file I usually write

cat my_file | while read a
do
gzip "$a"
done

The gzip is just an example it can be anything.

What I'm wondering is if there is another way to get the lines than cat file | while read?

share|improve this question

3 Answers 3

up vote 8 down vote accepted

You don't need to use cat:

while read line; do
    echo "$line"
done < my_file

I don't think there's a simpler way though.

share|improve this answer
1  
+1 In addition to avoiding a UUoC, doing it this way also prevents creating a subshell so the variables set during the loop will still be available after the loop (also you will still be in a directory that you cd to, if you do that). –  Dennis Williamson Jan 15 '11 at 20:58
    
+1 best so far. –  Nifle Jan 16 '11 at 0:26

The simplest, I think, would be to use xargs, e.g.,

xargs -L1 gzip < my_file

The -L1 option tells xargs to process one input line at a time. You might take a look at GNU parallel, too, which is very similar to xargs but more powerful in some situations.

share|improve this answer
IFS="\n\b"; for i in $MYROWOFCONTENT; do echo $i; done;
share|improve this answer

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.