用一个文件替换多个文件

用一个文件替换多个文件

想象一下我的目录如下所示:

./original.txt
./blah.1.txt
./blah.2.txt
[...]
./blah.999999.txt

我本质上想blah.*用 的内容替换每个文件original。我最初的尝试是这样做:

$ cp original.txt blah.*

但我明白:

cp: target ``blah.1.txt' is not a directory

答案1

只需再选择一个选项tee

cat original.txt | tee blah.*

以下是一个测试案例,您可以在负责任的成年人的监督下在家中尝试:

$ echo "rawr" | tee blah.{1..99}.txt
rawr

$ ls
blah.10.txt  blah.26.txt  blah.41.txt  blah.57.txt  blah.72.txt  blah.88.txt
blah.11.txt  blah.27.txt  blah.42.txt  blah.58.txt  blah.73.txt  blah.89.txt
blah.12.txt  blah.28.txt  blah.43.txt  blah.59.txt  blah.74.txt  blah.8.txt
blah.13.txt  blah.29.txt  blah.44.txt  blah.5.txt   blah.75.txt  blah.90.txt
blah.14.txt  blah.2.txt   blah.45.txt  blah.60.txt  blah.76.txt  blah.91.txt
blah.15.txt  blah.30.txt  blah.46.txt  blah.61.txt  blah.77.txt  blah.92.txt
blah.16.txt  blah.31.txt  blah.47.txt  blah.62.txt  blah.78.txt  blah.93.txt
blah.17.txt  blah.32.txt  blah.48.txt  blah.63.txt  blah.79.txt  blah.94.txt
blah.18.txt  blah.33.txt  blah.49.txt  blah.64.txt  blah.7.txt   blah.95.txt
blah.19.txt  blah.34.txt  blah.4.txt   blah.65.txt  blah.80.txt  blah.96.txt
blah.1.txt   blah.35.txt  blah.50.txt  blah.66.txt  blah.81.txt  blah.97.txt
blah.20.txt  blah.36.txt  blah.51.txt  blah.67.txt  blah.82.txt  blah.98.txt
blah.21.txt  blah.37.txt  blah.52.txt  blah.68.txt  blah.83.txt  blah.99.txt
blah.22.txt  blah.38.txt  blah.53.txt  blah.69.txt  blah.84.txt  blah.9.txt
blah.23.txt  blah.39.txt  blah.54.txt  blah.6.txt   blah.85.txt
blah.24.txt  blah.3.txt   blah.55.txt  blah.70.txt  blah.86.txt
blah.25.txt  blah.40.txt  blah.56.txt  blah.71.txt  blah.87.txt

$ cat blah.67.txt 
rawr

$ echo "hooray" > original.txt

$ cat original.txt | tee blah.*.txt
hooray

$ cat blah.67.txt 
hooray

答案2

使用 bash for(假设您正在使用 bash):

for file in blah.*.txt; do
    cp original.txt "$file"
done

答案3

您可以尝试这样做,避免 for 循环并将内容保持在一行中:

ls blah.* | xargs -n 1 cp original

cp: target blah.1.txt is not a directory最初的尝试失败了,因为 cp 多个文件假设将它们全部移动到最后一个参数提供的目录中。这完全是错误的语法。引用man cp

SYNOPSIS
       cp [OPTION]... [-T] SOURCE DEST
       cp [OPTION]... SOURCE... DIRECTORY
       cp [OPTION]... -t DIRECTORY SOURCE...

DESCRIPTION
       Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.

仅使用cp不会帮助你。另请参阅这个问题

答案4

下面是另一个使用选项find

find ./ -name 'blah.*.txt' -exec cp original.txt {} \;

您要求find从当前目录开始并查找名称与模式匹配的文件(用引号引起来,以避免 shell 扩展它并让 find 进行模式扩展),并且对于找到的每个文件,执行 和 之间的命令-exec\;在此命令中,{}替换为找到的文件的名称。

看看这个答案,获得大量关于find有效使用的信息:

如何更有效地使用 find 命令?

相关内容