如何在shell脚本中复制和重命名文件

时间:2012-09-17 01:16:47

标签: shell copy rename

我有一个文件夹“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

你能帮我吗?

2 个答案:

答案 0 :(得分:0)

此代码可以让您关闭。我试图准确记录我在做什么。

它确实依赖于BASH和find的GNU版本来处理文件名中的空格。我在.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

答案 1 :(得分:0)

#!/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