[英]How to copy and rename files in shell script
I have a folder "test" in it there is 20 other folder with different names like A,B ....(actually they are name of people not A, B...) I want to write a shell script that go to each folder like test/A and rename all the .c files with A[1,2..] and copy them to "test" folder. 我有一个文件夹“ test”,其中还有其他20个文件夹,它们的名称不同,例如A,B...。(实际上,它们是人的名字,而不是A,B ...)我想编写一个shell脚本每个文件夹(例如test / A),并使用A [1,2 ..]重命名所有.c文件,然后将其复制到“ test”文件夹。 I started like this but I have no idea how to complete it!
我是这样开始的,但是我不知道如何完成它!
#!/bin/sh
for file in `find test/* -name '*.c'`; do mv $file $*; done
Can you help me please? 你能帮我吗?
This code should get you close. 此代码应该使您接近。 I tried to document exactly what I was doing.
我试图准确记录我在做什么。
It does rely on BASH and the GNU version of find to handle spaces in file names. 它确实依靠BASH和find的GNU版本来处理文件名中的空格。 I tested it on a directory fill of .DOC files, so you'll want to change the extension as well.
我在.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
#!/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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.