bash 循环遍历目录中的所有文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8512462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Looping through all files in a directory
提问by skline
I want to write a shell script that will loop through all the files in a directory and echo "put ${filename}". Can anyone point me in the right direction?
我想编写一个 shell 脚本,它将遍历目录中的所有文件并回显“put ${filename}”。任何人都可以指出我正确的方向吗?
回答by Oliver Charlesworth
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.
有关递归解决方案,请参阅 Bennet Yee 的回答。
回答by Bennet Yee
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 {}" \;
回答by Kevin
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.
如果要包含文件夹本身,请取出该-type f
部分。
回答by Mad-D
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
回答by jcollado
One more alternative using ls
and sed
:
使用ls
and 的另一种选择sed
:
$ ls -1 <dir> | sed -e 's/^/put /'
and using ls
and xargs
:
并使用ls
和xargs
:
$ ls -1 <dir> | xargs -n1 -i%f echo 'put %f'
回答by Vijay
this will work also recursively if you have any sub directories and files inside them:
如果其中有任何子目录和文件,这也将递归地工作:
find . -type f|awk -F"/" '{print "put ",$NF}'