我有一个像这样的文件列表
186866-Total-Respondents.csv
343764-Total-Respondents.csv
415612-Total-Respondents.csv
761967-Total-Respondents.csv
我想通过将上面的第一个数字字符串与同一目录中名为data.txt的文件中的相同数字字符串进行匹配来重命名它们。
data.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
我发现有一个similar question,它使用sed和regex,但是我无法编辑该regex来成功重命名。
我猜sed或awk在这里能很好地工作?
答案 0 :(得分:1)
# 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 "%s\n" *.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
答案 1 :(得分:1)
如果您有这两个文件,并且想要使用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