I use the following Bash Shell script to list the ".txt" files recursively under 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 under the current directory have spaces in their names, e.g. "my testing.txt". The listing becomes corrupted, e.g. "my testing.txt" is listed as
my
testing.txt
It seems that the "for" loop uses "white space" (space, \n etc) to separate the file list but in my case I want to use only "\n" to separate the file list.
Is there any way I could modify this script to achieve this purpose. Any idea.
Thanks in advance.
To see a list of all subdirectories and files within your current working directory, use the command ls .
The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).
To loop through a directory, and then print the name of the file, execute the following command: for FILE in *; do echo $FILE; done.
If you're using bash 4, just use a 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 quote "$file"
or you'll have the same problem elsewhere. **
will recursively match files and directories if you have enabled globstar
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With