我需要根据另一个文件中的匹配字符串重命名文件



我有一个这样的文件列表

186866-Total-Respondents.csv
343764-Total-Respondents.csv
415612-Total-Respondents.csv
761967-Total-Respondents.csv

我想通过将上面的第一串数字与名为 data 的文件中的同一串数字相匹配来重命名它们.txt该文件位于同一目录中。

数据内容.txt如下

2018-09-Client-1-761967-Brand-1-Total-Respondents
2018-09-Client-1-415612-Brand-2-Two-Total-Respondents
2018-09-Client-1-186866-Brand-Three-Total-Respondents
2018-09-Client-2-343764-Brand1-Total-Respondents
2018-09-Client-3-347654-No-Name-Brand-Total-Respondents
2018-09-Client-3-109321-House-Brand-Total-Respondents

最终结果是上面的 4 个匹配文件将被重命名为

2018-09-Client-1-186866-Brand-Three-Total-Respondents.csv
2018-09-Client-2-343764-Brand1-Total-Respondents.csv
2018-09-Client-1-415612-Brand-2-Two-Total-Respondents.csv
2018-09-Client-1-761967-Brand-1-Total-Respondents.csv

我发现了一个类似的问题,它使用 sed 和正则表达式,但我无法编辑正则表达式以成功重命名。

我猜 sed 或 awk 在这里会很好用吗?

如果您有这两个文件,并且想使用awk来执行此操作,那么这有效:

awk -F "-" '(NR==FNR){a[$1]=$0;next}
($5 in a){system("mv "a[$5]" "$0".csv)}' file1 file2

file1文件列表并file2数据文件。

另一种方法是,如果您只有数据文件,

#!/usr/bin/env bash
while read -r line; do          # read a full line from data.txt
IFS="-" read -r a a a a value a <<<"${line}"
old="${value}-Total-Respondents.csv";  # build old name
[[ -e "${old}" ]] && mv "${old}" "${line}.csv" # move if file exists
done < data.txt
# you have list of files
touch 186866-Total-Respondents.csv 343764-Total-Respondents.csv  415612-Total-Respondents.csv 761967-Total-Respondents.csv
# and data.txt
cat >data.txt <<EOF
2018-09-Client-1-761967-Brand-1-Total-Respondents
2018-09-Client-1-415612-Brand-2-Two-Total-Respondents
2018-09-Client-1-186866-Brand-Three-Total-Respondents
2018-09-Client-2-343764-Brand1-Total-Respondents
2018-09-Client-3-347654-No-Name-Brand-Total-Respondents
2018-09-Client-3-109321-House-Brand-Total-Respondents
EOF
# and you need to join them on the first field from list and the 5th field from data
# got a little `while read` there, cause I got no good idea how to replace 4th occurence of char with a tab or space
# also I needed to add `.csv` suffix to the data.txt, but I could have just `sed 's/$/.csv/'
# xargs then eats every two arguments and runs mv
join -11 -25 -t- <(printf "%sn" *.csv | sort) <(<data.txt sort -t- -k5) 
| while IFS=- read -r a b c r; do echo "$a-$b-$c" "$r".csv; done 
| xargs -n2 mv

脚本将执行:

mv 186866-Total-Respondents.csv 2018-09-Client-1-Brand-Three-Total-Respondents.csv
mv 343764-Total-Respondents.csv 2018-09-Client-2-Brand1-Total-Respondents.csv
mv 415612-Total-Respondents.csv 2018-09-Client-1-Brand-2-Two-Total-Respondents.csv
mv 761967-Total-Respondents.csv 2018-09-Client-1-Brand-1-Total-Respondents.csv

最新更新