How to prevent file name extension for loop in bash

In a for loop like this

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

if one of the input files contains entries of type *a , it will be and gives file names ending in 'a'.

Is there an easy way to prevent the extension of this name?

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

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

still causes the extension *a , and

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

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

+4
source share
2 answers

This will be the cat contents of all files and will repeat along the lines of the result:

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

If files contain wildcards, they will not be expanded. They should not use for and indicate your variable.

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

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

The reason this is not done in Bash is because it creates a subshell and when you exit the loop, the values โ€‹โ€‹of the variables set inside and any changes to the cd directory will be lost.

+4
source

In the example above, a simple cat *.input will do the same.

0
source

Source: https://habr.com/ru/post/1341236/


All Articles