bash - 根据列表和文件目录重命名文件列表
问题描述
所以,我有一个主文件 - countryCode.tsv,它是这样的,
01 united_states
02 canada
etc.
我有另一个国家文件列表,如下所示,
United_states.txt
Wyoming
Florida
etc.
加拿大.txt
some
blah
shit
etc.
而且,我有一个这样命名的文件列表,
01_1
01_2
02_1
02_2
etc.
文件名的第一部分属于第一个列表中的国家代码,第二部分属于国家文件的行号。
例如,
01_02
将包含与佛罗里达(美国)相关的信息。
现在,我的问题来了,
我如何将这些以数字命名的文件重命名为 country_state 格式,例如,
01_02
变成united_states_florida
解决方案
我这样做的方法是首先将所有国家/地区读入一个关联数组,然后我将遍历该数组以查找每个国家/地区的“.txt”文件。当我找到一个时,依次读取每一行并从该文件中查找与国家代码和行号匹配的文件。如果找到,请重命名。
这是一些示例代码:
#!/bin/bash
declare -A countries # countries is an associative array.
while read code country; do
if [ ${#code} -ne 0 ]; then # Ignore blank lines.
countries[${code}]=${country}
fi
done < countryCodes.txt # countryCodes.txt is STDIN for the while
# loop, which is passed on to the read command.
for code in ${!countries[@]}; do # Iterate over the array indices.
counter=0
country=${countries[${code}]}
if [ -r "${country}.txt" ]; then # In case country file does not exist.
while read state; do
((counter++))
if [ -f "${code}_${counter}" ]; then
mv "${code}_${counter}" "${country}_${state}"
fi
done < "${country}.txt"
fi
done
推荐阅读
- android-jetpack-compose - Jetpack Compose animateScrollTo 到绝对坐标或直接到元素
- javascript - 无法使用 document.getElementById 获取元素
- amazon-web-services - 我可以使用注入 AWS AppMesh 的 envoy 自定义访问日志吗?
- java - JSch SFTP 连接卡住
- java - 如何使用 java 将日期格式化为 01-JAN-2021
- amcharts - Amcharts:列系列图表中的多类别轴网格对齐问题
- amazon-web-services - 通过 CloudFormation 向现有 VPC Endpoint 添加安全组
- python - 从列表中找到三个加起来等于特定数字的数字
- python-3.x - 有没有办法在 scipy.optimize 中访问 curve_fit 的内部状态?
- sql - 如何从最后一个父级的行中获取数据