4

In a for loop like this,

for i in `cat *.input`; do
    echo "$i"
done

if one of the input file contains entries like *a, it will, and give the filenames ending in 'a'.

Is there a simple way of preventing this filename expansion?

Because of use of multiple files, globbing (set -o noglob) is not a good option. I should also be able to filter the output of cat to escape special characters, but

for i in `cat *.input | sed 's/*/\\*'`
    ...

still causes *a to expand, while

for i in `cat *.input | sed 's/*/\\\\*'`
    ...

gives me \*a (including backslash). [ I guess this is a different question though ]

cagri
  • 43
  • 4
  • Do you want to do something with each line or with each word in the input files? Because if one of the input files contains e.g. foo bar.txt then the for loop would do one iteration with i set to foo, and one with i set to bar.txt – a.peganz May 10 '16 at 14:48

2 Answers2

5

This will cat the contents of all the files and iterate over the lines of the result:

while read -r i
do
    echo "$i"
done < <(cat *.input)

If the files contain globbing characters, they won't be expanded. They keys are to not use for and to quote your variable.

In Bourne-derived shells that do not support process substitution, this is equivalent:

cat *.input | while read -r i
do
    echo "$i"
done

The reason not to do that in Bash is that it creates a subshell and when the subshell (loop) exits, the values of variables set within and any cd directory changes will be lost.

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
0

For the example you have, a simple cat *.input will do the same thing.

Satya
  • 4,458
  • 21
  • 29
  • Thanks & and sorry for not stating earlier, but the scrip is way too complicated dump here. `echo $i` is just a placeholder (`cat` in the for loop is also a complex combination of grep/sed/cut). If I can get this `echo` statement to print what is in the file literally, the rest will be solved. – cagri Feb 25 '11 at 00:04