首页 > 解决方案 > 根据列表和文件目录重命名文件列表

问题描述

所以,我有一个主文件 - 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

标签: bash

解决方案


我这样做的方法是首先将所有国家/地区读入一个关联数组,然后我将遍历该数组以查找每个国家/地区的“.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

推荐阅读