[英]Batch Rename a file based of part of name of second file
I want to batch rename some file based of Part of Name of other files我想根据其他文件的部分名称批量重命名某些文件
let me explain my question with a example, I think its better in this way让我用一个例子来解释我的问题,我认为这样更好
I have some file with these name in a folder我在文件夹中有一些具有这些名称的文件
sc_gen_08-bigfile4-0-data.txt
signal_1_1-bigfile8.1-0-data.txt
and these file in other folder这些文件在其他文件夹中
sc_gen_08-acaaf2d4180b743b7b642e8c875a9765-1-data.txt
signal_1_1-dacaaf280b743b7b642e8c875a9765-4-data.txt
I want to batch rename first files to name of second files, how can I do this?我想将第一个文件批量重命名为第二个文件的名称,我该怎么做? also file in both first and second folder have common in name第一个和第二个文件夹中的文件也有共同的名称
name(common in file in both folder)-[only this part is diffrent in each file]-data.txt
Thanks (sorry if its not a good question for everyone, but its a question for me)谢谢(对不起,如果这对每个人来说都不是一个好问题,但对我来说是个问题)
Let's name the original folder as "folder1" and the other folder as "folder2".让我们将原始文件夹命名为“folder1”,将另一个文件夹命名为“folder2”。 Then would you please try the following:那么请您尝试以下方法:
#!/bin/bash
folder1="folder1" # the original folder name
folder2="folder2" # the other folder name
declare -A map # create an associative array
for f in "$folder2"/*-data.txt; do # find files in the "other folder"
f=${f##*/} # remove directory name
common=${f%%-*} # extract the common substring
map[$common]=$f # associate common name with full filename
done
for f in "$folder1"/*-data.txt; do # find files in the original folder
f=${f##*/} # remove directory name
common=${f%%-*} # extract the common substring
mv -- "$folder1/$f" "$folder1/${map[$common]}"
# rename the file based on the value in map
done
If your files are all called as you mentioned.如果您的文件都像您提到的那样被调用。 I have created the next script.我创建了下一个脚本。
It is located following the next structure.它位于下一个结构之后。
root@vm:~/test# ll
folder1/
folder2/
script.sh
The script is the next:脚本是下一个:
#Declare folders
folder1=./folder1
folder2=./folder2
#Create new folder if it does not exist
if [ ! -d ./new ]; then
mkdir ./new;
fi
#Iterate over first directory
for file1 in folder1/*; do
#Iterate over second directory
for file2 in folder2/*; do
#Compare begining of each file, if they match, they will be copied.
if [[ $(basename $file1 | cut -f1 -d-) == $(basename $file2 | cut -f1 -d-) ]]; then
echo $(basename $file1) $(basename $file2) "Match"
cp folder1/$(basename $file1) new/$(basename $file2)
fi
done
done
It creates a folder called new and will copy all your files there.它会创建一个名为 new 的文件夹,并将您的所有文件复制到那里。 If you want to delete them, use mv instead.如果要删除它们,请改用 mv 。 But I didn't want to use mv in the first attempt just in case to get some undesired effect.但我不想在第一次尝试时使用 mv 以防万一得到一些不希望的效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.