Shellscript Looping Through All Files in a Folder

2019-01-09 10:10发布

问题:

I want to write a shellscript that will loop through all the files in a folder and echo "put ${filename}". Can anyone point me in the right direction?

回答1:

For files and directories, not recursive

for filename in *; do echo "put ${filename}"; done

For files only (excludes folders), not recursive

for file in *; do 
    if [ -f "$file" ]; then 
        echo "$file" 
    fi 
done

For a recursive solution, see Bennet Yee's answer.



回答2:

recursively, including files in subdirectories?

find dir -type f -exec echo "put {}" \;

only files in that directory?

find dir -maxdepth 1 -type f -exec echo "put {}" \;


回答3:

For all folders and files in the current directory

for file in *; do
    echo "put $file"
done

Or, if you want to include subdirectories and files only:

find . -type f -exec echo put {} \;

If you want to include the folders themselves, take out the -type f part.



回答4:

If you don't have any files, then instead of printing * we can do this.

format=*.txt
for i in $format;
do
 if [[ "$i" == "$format" ]]
 then
    echo "No Files"
 else
    echo "file name $i"
 fi
done


回答5:

One more alternative using ls and sed:

$ ls -1 <dir> | sed -e 's/^/put /'

and using ls and xargs:

$ ls -1 <dir> | xargs -n1 -i%f echo 'put %f'


回答6:

this will work also recursively if you have any sub directories and files inside them:

find . -type f|awk -F"/" '{print "put ",$NF}'


标签: bash shell loops