代码之家  ›  专栏  ›  技术社区  ›  Patrick McElhaney

Bash One Liner:将template_*.txt复制到foo_*.txt?

  •  9
  • Patrick McElhaney  · 技术社区  · 16 年前

    假设我有三个文件(template_*.txt):

    • templatex.txt
    • template_y.txt
    • template_z.txt

    我想将它们复制到三个新文件(foo_*.txt)中。

    • foo.x.txt
    • fooy.txt
    • foo_z.txt

    是否有一些简单的方法可以通过一个命令来实现这一点,例如。

    cp --enableAwesomeness template_*.txt foo_*.txt

    8 回复  |  直到 16 年前
        1
  •  11
  •   Orion Edwards    16 年前
    对于template_*.txt中的f;执行cp$f foo${f#template_};结束
    
        2
  •  3
  •   Matt McMinn    16 年前
    [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
    
        3
  •  3
  •   Roberto Bonvallet    13 年前

    我喜欢的方式:

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

    “我不记得替换语法”的方式:

    for i in x y z
    do
      cp template_$i foo_$
    done
    
        4
  •  2
  •   Chris Bartow    16 年前

    这应该奏效:

    for file in template_*.txt ; do cp $file `echo $file | sed 's/template_\(.*\)/foo_\1/'` ; done
    
        5
  •  1
  •   pauldoo    16 年前
    for i in template_*.txt; do cp -v "$i" "`echo $i | sed 's%^template_%foo_%'`"; done
    

    如果你的文件名中有时髦的字符,可能会中断。当(如果)你确信它可靠工作时,删除“-v”。

        6
  •  1
  •   Bruno De Fraine    16 年前

    命令 mmv (可在 Debian Fink 或者易于自己编译)正是为此任务创建的。使用普通的Bash解决方案,我总是需要查找有关变量扩展的文档。但是 mmv 使用起来要简单得多,非常接近“真棒”! ;-)

    你的例子是:

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

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

        7
  •  1
  •   Blair Conrad    16 年前

    我不知道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
    
        8
  •  0
  •   Jon Ericson Homunculus Reticulli    16 年前

    还有另一种方法:

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

    我一直对ImageMagick印象深刻 convert 该程序可以按照您的期望处理图像格式:

    $ convert rose.jpg rose.png
    

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

    $ mogrify -format png *.jpg
    

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