There are lots of ways to achieve this in Bash. Below are the two most common:
Process Substitution
This approach is preferred because it does not create a sub-shell, which can play havoc with variables. That said, the syntax is a bit more clunky.
The following code will read file.txt line by line and reverse then print each line:
do
echo $line | rev
done < <(cat file.txt)
The following code will cat all of the files in the current directory and replace foo with bar in each file:
do
cat $line | sed 's/foo/bar/g'
done < <(ls -1)
Subshell
Although not ideal for some situations, this is a simpler syntax which I prefer to use:
The following code will read file.txt line by line and reverse then print each line:
do
echo $line | rev
done
The following code will cat all of the files in the current directory and replace foo with bar in each file:
do
cat $line | sed 's/foo/bar/g'
done
Summary
In all of the above examples, while read line
creates a variable called $line which you can use inside the loop.
Note that the above are just examples. There are better ways to do the things they do.
Just to let you know, both of those examples contain what is known as “useless uses of cat”. It shows bad coding practice for bash scripts, opening up more processes than are necessary. Google ‘useless uses of cat’ for more information on this common faux-pas.
The following does the same, without the waste of a cat:
while read line; do
echo $line | rev
done < file.txt
#==========
ls -1 | while read line
do
sed 's/foo/bar/g' < $line
done