如何一步复制并添加文件名前缀?

Bla*_*Cat 12 bash cp file-copy

我想复制和重命名一个目录中的多个 c 源文件。

我可以这样复制:

$ cp *.c $OTHERDIR
Run Code Online (Sandbox Code Playgroud)

但我想给所有文件名一个前缀:

file.c --> old#file.c
Run Code Online (Sandbox Code Playgroud)

我怎样才能在 1 步中做到这一点?

gle*_*man 23

一个for循环:

for f in *.c; do cp -- "$f" "$OTHERDIR/old#$f"; done
Run Code Online (Sandbox Code Playgroud)

我经常添加-v选项以cp允许我观看进度。


ter*_*don 7

您可以使用 shell globbing:

for f in *.c; do cp -- "$f" "$OTHERDIR/old#$f"; done
Run Code Online (Sandbox Code Playgroud)

for variable in GLOB格式会将glob扩展到所有匹配的文件/目录(不包括隐藏文件)并遍历它们,依次将每个文件保存为$variable(在上面的示例中,$f)。因此,我显示的命令将遍历所有非隐藏文件,复制它们并添加前缀。