BASH: Reading Text File

BASH for C programmers:

Read a text file word-by-word in BASH:
#!/bin/bash
for WORD in `cat filename`
do
    echo $WORD
done
Read a text file line-by-line in BASH:
#!/bin/bash
while read LINE
do
    echo $LINE
done < filename
Looping in BASH:
i=0
while [ $i -lt 10 ]
do
    echo $i

    # next
    i=$(($i+1))
done
Update: another way to loop suggested in the comment.

Comments

JW said…
Thanks! Nice and succinct.
Unknown said…
you really should use a for loop for that last one:

for (( i = 1; i <= 10; i++ )); do echo $i ; done
Unknown said…
I agree with JW. Tnx.
tep said…
Glad it helps! Thanks Alan for the suggestion. I updated the post so that it has nice syntax highlighting.
etch1 said…
thanks dood! :)
pawelk said…
thanks for this post; it was helpful

Popular posts from this blog

World, View and Projection Matrix Internals

GDC 2015 Links