bash 中的通配符
Wildcards in bash
假设我有两个文件夹(存储在我的主目录中)dir1
和 dir2
,它们都包含一个同名文件,比如 hello_world.txt
。但是,每个 hello_world.txt
文件的内容 不同 。
我可以
ls dir*/hello_world.txt
dir1/hello_world.txt dir2/hello_world.txt
这将列出这两个文件。那太棒了!但是...
如何复制这两个文件,使用*
通配符,和 同时重新命名它们。 即我希望输出为
hello_world1.txt hello_world2.txt
并将其放在我的主目录中。
for 循环确实是这里最好的解决方案:它清晰、可维护,而且尽管是多行的,但非常简单:
i=0
for hw in dir*/hello_world.txt; do
dest="$HOME/${hw##*/}"
cp "$hw" "${dest%.*}$((++i)).txt"
done
输入:
$ tree
.
├── dir1
│ └── hello_world.txt
└── dir2
└── hello_world.txt
输出:
$ tree
.
├── dir1
│ ├── hello_world.txt
└── dir2
└── hello_world.txt
$ (cd ~ && tree)
.
├── hello_world1.txt
└── hello_world2.txt
GNU Coreutils 有一个选项 -b
到 cp
可以让你避免覆盖文件。
cp -b numbered dir*/hello_world.txt $HOME
但是,这并不能完全控制生成的名称。
有关详细文档,请参阅 Coreutils 文档中的 info coreutils cp
and Backup options。
假设我有两个文件夹(存储在我的主目录中)dir1
和 dir2
,它们都包含一个同名文件,比如 hello_world.txt
。但是,每个 hello_world.txt
文件的内容 不同 。
我可以
ls dir*/hello_world.txt
dir1/hello_world.txt dir2/hello_world.txt
这将列出这两个文件。那太棒了!但是...
如何复制这两个文件,使用*
通配符,和 同时重新命名它们。 即我希望输出为
hello_world1.txt hello_world2.txt
并将其放在我的主目录中。
for 循环确实是这里最好的解决方案:它清晰、可维护,而且尽管是多行的,但非常简单:
i=0
for hw in dir*/hello_world.txt; do
dest="$HOME/${hw##*/}"
cp "$hw" "${dest%.*}$((++i)).txt"
done
输入:
$ tree
.
├── dir1
│ └── hello_world.txt
└── dir2
└── hello_world.txt
输出:
$ tree
.
├── dir1
│ ├── hello_world.txt
└── dir2
└── hello_world.txt
$ (cd ~ && tree)
.
├── hello_world1.txt
└── hello_world2.txt
GNU Coreutils 有一个选项 -b
到 cp
可以让你避免覆盖文件。
cp -b numbered dir*/hello_world.txt $HOME
但是,这并不能完全控制生成的名称。
有关详细文档,请参阅 Coreutils 文档中的 info coreutils cp
and Backup options。