Bash Shell List Files Using the "for" Loop

I use the following Bash shell script to list the ".txt" files recursively in the current directory:

#!/bin/bash for file in $( find . -type f -name "*.txt" ) do echo $file # Do something else. done 

However, some of the .txt files in the current directory have spaces in their names, for example. "my testing.txt". The listing is getting corrupted, for example. "my testing.txt" is listed as

 my testing.txt 

It seems that the for loop uses a space (space, \ n, etc.) to split the list of files, but in my case I want to use only "\ n" to split the list of files.

Is there any way to modify this script to achieve this. Any idea.

Thanks in advance.

+6
source share
2 answers

If you are using bash 4, just use glob:

 #!/bin/bash shopt -s globstar for file in **/*.txt do if [[ ! -f "$file" ]] then continue fi echo "$file" # Do something else. done 

Be sure to specify "$file" or you will have the same problem elsewhere. ** will recursively match files and directories if you enabled globstar .

+7
source

Yes, there is find to separate file names with NUL and use read to distinguish between NUL . This will successfully iterate over any file name, since NUL is not a valid character for the file name.

 #!/bin/bash while IFS= read -r -d '' file; do echo "$file" # Do something else. done < <(find . -type f -name "*.txt" -print0) 

Alternatively, if # do something else not too complicated, you can use the find -exec option and not worry about the proper demarcation

+7
source

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


All Articles