0

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

你能帮我吗?

4

2 回答 2

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
于 2014-05-07T16:06:42.167 回答
0

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

它确实依赖 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
于 2012-09-17T01:45:49.260 回答