重击一线:将template _ *。txt复制到foo _ *。txt?

时间:2020-03-05 18:42:54  来源:igfitidea点击:

假设我有三个文件(template _ *。txt):

  • template_x.txt
  • template_y.txt
  • template_z.txt

我想将它们复制到三个新文件(foo _ *。txt)。

  • foo_x.txt
  • foo_y.txt
  • foo_z.txt

是否有一些简单的方法可以使用一个命令来执行此操作,例如

cp --enableAwesomeness template _ *。txt foo _ *。txt`

解决方案

回答

我不知道bash或者cp上的任何内容,但是有一些简单的方法可以使用(例如)一个perl脚本来完成这种事情:

($op = shift) || die "Usage: rename perlexpr [filenames]\n";

for (@ARGV) {
    $was = $_;
    eval $op;
    die $@ if $@;
    rename($was,$_) unless $was eq $_;
}

然后:

rename s/template/foo/ *.txt

回答

for i in template_*.txt; do cp -v "$i" "`echo $i | sed 's%^template_%foo_%'`"; done

如果文件名中包含时髦字符,则可能会中断。当(如果)确信它可以可靠运行时,请删除" -v"。

回答

这应该工作:

for file in template_*.txt ; do cp $file `echo $file | sed 's/template_\(.*\)/foo_/'` ; done

回答

[01:22 PM] matt@Lunchbox:~/tmp/ba$
ls
template_x.txt  template_y.txt  template_z.txt

[01:22 PM] matt@Lunchbox:~/tmp/ba$
for i in template_*.txt ; do mv $i foo${i:8}; done

[01:22 PM] matt@Lunchbox:~/tmp/ba$
ls
foo_x.txt  foo_y.txt  foo_z.txt

回答

for f in template_*.txt; do cp $f foo_${f#template_}; done

回答

还有另一种方法:

$ ls template_*.txt | sed -e 's/^template\(.*\)$/cp template foo/' | ksh -sx

ImageMagick转换程序给我留下了深刻的印象,该程序可以实现我们期望的图像格式:

$ convert rose.jpg rose.png

它有一个允许批量转换的姊妹程序:

$ mogrify -format png *.jpg

显然,这些仅限于图像转换,但是它们具有有趣的命令行界面。

回答

专门为此任务创建了命令" mmv"(在Debian或者Fink中可用,或者很容易自己编译)。使用普通的Bash解决方案,我总是必须查找有关变量扩展的文档。但是mmv更易于使用,非常接近"令人敬畏"! ;-)

示例将是:

mcp "template_*.txt" "foo_#1.txt"

mmv也可以处理更复杂的模式,并且具有一些健全性检查,例如,它将确保目标集中的所有文件都不会出现在源集中(因此,我们不会意外覆盖文件)。

回答

我的首选方式:

for f in template_*.txt
do
  cp $f ${f/template/foo}
done

"我不记住替代语法"的方式:

for i in x y z
do
  cp template_$i foo_$
done