我正在编写一个脚本,需要在特定文件夹的每个子目录中执行一个操作。
最有效的写法是什么?
我正在编写一个脚本,需要在特定文件夹的每个子目录中执行一个操作。
最有效的写法是什么?
当前回答
找到。-type d -print0 | xargs -0 -n 1 my_command
其他回答
找到。-type d -print0 | xargs -0 -n 1 my_command
使用find命令。
在GNU find中,你可以使用-execdir参数:
find . -type d -execdir realpath "{}" ';'
或者使用-exec parameter:
find . -type d -exec sh -c 'cd -P "$0" && pwd -P' {} \;
或者使用xargs命令:
find . -type d -print0 | xargs -0 -L1 sh -c 'cd "$0" && pwd && echo Do stuff'
或者使用for循环:
for d in */; { echo "$d"; }
对于递归,请尝试扩展通配符(**/)(通过:shopt -s extglob启用)。
有关更多示例,请参见:如何进入每个目录并执行命令?在所以
如果你想在文件夹内而不是在文件夹上执行操作。
说明:您有许多pdf文件,希望将它们集中在一个文件夹中。 我的文件夹
AV 001/
AV 002/
for D in *; do cd "$D"; # VERY DANGEROUS COMMAND - DONT USE #-- missing "", it will list files too. It can go up too. for d in */; do cd "$d"; echo $d; cd ..; done; # works succesfully for D in "$(ls -d */)"; do cd "$D"; done; # bash: cd: $'Athens Voice 001/\nAthens Voice 002/' - there is no such folder for D in "$(*/)"; do cd "$D"; done; # bash: Athens Voice 001/: is folder for D in "$(`find . -type d`)"; do cd $D; done; # bash: ./Athens: there is no such folder or file for D in *; do if [ -d "${D}" ] then cd ${D}; done; # many arguments
for D in `find . -type d`
do
//Do whatever you need with D
done
你可以试试:
#!/bin/bash
### $1 == the first args to this script
### usage: script.sh /path/to/dir/
for f in `find . -maxdepth 1 -mindepth 1 -type d`; do
cd "$f"
<your job here>
done
或类似的…
解释:
找到。-maxdepth 1 -mindepth 1 type d: 只查找最大递归深度为1(仅为$1的子目录)和最小递归深度为1(不包括当前文件夹)的目录。