我想我会把它放在这里,以帮助其他可能需要它的人。
我有一个名为 spreadsheet.csv 的文件,它位于服务器上的 500 个不同位置。经过一堆试验和错误,我确定了这个解决方案来复制该文件的每个实例,重命名它(按增量)并将其复制到不同的文件夹中。
希望这对某人有所帮助!
COUNTER=0;
for f in $(find folder/ -name 'spreadsheet.csv');
do
cp -v $f /new/location/spreadsheet$COUNTER.csv;
COUNTER=$[$COUNTER+1];
done
一个简单的bash
for-loop
可以实现这一点:-
COUNTER="0"
fileName="spreadsheet.csv"
for file in $(find folder/ -name "$fileName" -type f -printf '%Pn');
do
sourcePath=$(dirname $(readlink -f "$file"))
cp -v $sourcePath/$fileName /new/location/"$fileName$COUNTER"
COUNTER=$((COUNTER+1))
done
脚本的关键部分是获取每个文件的源路径,这是我通过readlink
和dirname
实现的。请参阅他们的man
页面以了解有关其描述的更多信息。
例:-
$ find . -name "spreadsheet.csv" -type f
./foo/spreadsheet.csv
./bar/spreadsheet.csv
./woo/spreadsheet.csv
./spreadsheet.csv
$ ./script.sh
`/home/dude/foo/spreadsheet.csv' -> `/new/location/spreadsheet.csv0'
`/home/dude/bar/spreadsheet.csv' -> `/new/location/spreadsheet.csv1'
`/home/dude/woo/spreadsheet.csv' -> `/new/location/spreadsheet.csv2'
`/home/dude/spreadsheet.csv' -> `/new/location/spreadsheet.csv3'
如果至少一个目录名称中有空格或特殊字符,脚本将中断。
Inian对符号链接的看法也是对的。
下面有一个安全且标准的解决方案,其中仅搜索常规文件:
find folder/ -type f -name 'spreadsheet.csv' -printf "%p " | xargs -0 sh -c '
newlocdir=/new/location;
COUNTER=$(ls -1 "${newlocdir}"/spreadsheet*.csv 2>/dev/null | awk "END {print NR}") ;
for f ; do
cp -v "${f}" "${newlocdir}"/spreadsheet$COUNTER.csv;
COUNTER=$(($COUNTER+1));
done' dummyarg0
-printf "%p "
打印使用附加 NULL 找到的文件的路径名。
xargs -0
能够读取找到的文件,并将 NULL 字符视为条目之间的分隔符。
| awk "END {print NR}"
打印从管道读取的行数。
COUNTER=$(ls -1 "${newlocdir}"/spreadsheet*.csv 2>/dev/null | awk "END {print NR}")
将新位置中已存在的spreadsheet*.csv
文件的数量存储到 COUNTER 变量中。
for f ; do
读取位置参数;xargs
提供的文件名。
sh -c ' .... ' dummyarg0
sh
执行提供的命令。 dummyarg0
是必需的第一个参数。 sh
将特殊参数 0 的值设置为 dummyarg0
(未使用)。
测试:
$ find folder/
folder/
folder/dir2
folder/dir2/spreadsheet.csv
folder/foo bar
folder/foo bar/spreadsheet.csv
folder/spreadsheet.csv
folder/tr"uc
folder/tr"uc/spreadsheet.csv
folder/fo'o
folder/fo'o/spreadsheet.csv
folder/dir1
folder/dir1/spreadsheet.csv
$ find folder/ -type f -name 'spreadsheet.csv' -printf "%p " | xargs -0 sh -c '
newlocdir=.;
COUNTER=$(ls -1 "${newlocdir}"/spreadsheet*.csv 2>/dev/null | awk "END {print NR}") ;
for f ; do
cp -v "${f}" "${newlocdir}"/spreadsheet$COUNTER.csv;
COUNTER=$(($COUNTER+1));
done' dummyarg0
`folder/dir2/spreadsheet.csv' -> `./spreadsheet0.csv'
`folder/foo bar/spreadsheet.csv' -> `./spreadsheet1.csv'
`folder/spreadsheet.csv' -> `./spreadsheet2.csv'
`folder/tr"uc/spreadsheet.csv' -> `./spreadsheet3.csv'
`folder/fo'o/spreadsheet.csv' -> `./spreadsheet4.csv'
`folder/dir1/spreadsheet.csv' -> `./spreadsheet5.csv'