【问题标题】:How to copy and rename files in shell script如何在 shell 脚本中复制和重命名文件
【发布时间】:2012-09-09 05:55:23
【问题描述】:

我有一个文件夹“test”,里面还有 20 个不同名称的文件夹,比如 A,B ....(实际上他们是人的名字,而不是 A,B ...)我想写一个 shell 脚本转到像 test/A 这样的每个文件夹,并用 A[1,2..] 重命名所有 .c 文件并将它们复制到“test”文件夹。我是这样开始的,但我不知道如何完成它!

#!/bin/sh
for file in `find test/* -name '*.c'`; do mv $file $*; done

你能帮帮我吗?

【问题讨论】:

    标签: shell copy rename


    【解决方案1】:

    这段代码应该能让你接近。我试图准确记录我在做什么。

    它确实依赖 BASH 和 GNU 版本的 find 来处理文件名中的空格。我在 .DOC 文件的目录填充上对其进行了测试,因此您也需要更改扩展名。

    #!/bin/bash
    V=1
    SRC="."
    DEST="/tmp"
    
    #The last path we saw -- make it garbage, but not blank.  (Or it will break the '[' test command
    LPATH="/////" 
    #Let us find the files we want
    find $SRC -iname "*.doc" -print0 | while read -d $'\0' i
      do
      echo "We found the file name... $i";
    
      #Now, we rip off the off just the file name.
      FNAME=$(basename "$i" .doc)
      echo "And the basename is $FNAME";
      #Now we get the last chunk of the directory
      ZPATH=$(dirname "$i"  | awk -F'/' '{ print $NF}' )
      echo "And the last chunk of the path is... $ZPATH"
    
      # If we are down a new path, then reset our counter.
      if [ $LPATH == $ZPATH ]; then
        V=1
      fi;
      LPATH=$ZPATH
    
      # Eat the error message
      mkdir $DEST/$ZPATH 2> /dev/null 
      echo cp \"$i\" \"$DEST/${ZPATH}/${FNAME}${V}\"
      cp "$i" "$DEST/${ZPATH}/${FNAME}${V}"
    done
    

    【讨论】:

      【解决方案2】:
      #!/bin/bash
      
      ## Find folders under test. This assumes you are already where test exists OR give PATH before "test"
      folders="$(find test -maxdepth 1 -type d)"
      
      ## Look into each folder in $folders and find folder[0-9]*.c file n move them to test folder, right?
      for folder in $folders;
      do
         ##Find folder-named-.c files.
         leaf_folder="${folder##*/}"
         folder_named_c_files="$(find $folder -type f -name "*.c" | grep "${leaf_folder}[0-9]")"
      
         ## Move these folder_named_c_files to test folder. basename will hold just the file name.
         ## Don't know as you didn't mention what name the file to rename to, so tweak mv command acc..
         for file in $folder_named_c_files; do basename=$file; mv $file test/$basename; done
      done
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-27
        • 1970-01-01
        • 2016-03-14
        • 1970-01-01
        • 2013-05-02
        • 2021-12-19
        • 2011-04-20
        相关资源
        最近更新 更多