在bash中重命名文件夹名称

时间:2012-03-08 09:11:00

标签: bash directory rename

我需要重命名以下文件夹:

d_001_d  
d_001_h  
d_005_d  
d_005_h  
d_007_d  
d_007_h  

在:

d_a_d  
d_a_h  
d_b_d  
d_b_h  
d_c_d  
d_c_h  

所以基本上每个代码都对应一个名字(字母)。我试过了 sed命令和带有数组的for循环,但我无法完全得到我的信息 想。

感谢您的帮助

5 个答案:

答案 0 :(得分:3)

bos:$ ls
d_001_d  d_001_h  d_005_d  d_005_h  d_007_d  d_007_h
bos:$ for x in * ; do mv $x $(echo $x | sed -e 's/001/a/;s/005/b/;s/007/c/') ; done
bos:$ ls
d_a_d  d_a_h  d_b_d  d_b_h  d_c_d  d_c_h

答案 1 :(得分:1)

$ ls
d_001_d  d_001_h  d_005_d  d_005_h  d_007_d  d_007_h
$ ls | awk -F_ -v OFS=_ 'BEGIN{d["001"]="a"; d["005"]="b"; d["007"]="c"}; {old=$0; $2=d[$2]; printf("mv %s %s\n", old, $0)}' | bash
$ ls
d_a_d  d_a_h  d_b_d  d_b_h  d_c_d  d_c_h

答案 2 :(得分:1)

如果目录名称长度相同,则可以使用:

#!/bin/bash

for DIR in `ls */ -d`
do
    INDEX=${DIR:2:3}
    case $INDEX in
        001)
            LETTER="a"
            ;;
        005)
            LETTER="b"
            ;;
        007)
            LETTER="c"
            ;;
    esac
    mv "$DIR" ${DIR/$INDEX/$LETTER}
done

答案 3 :(得分:1)

没有硬编码number-> char映射:

chr() { [[ ${1} -lt 256 ]] || return 1; printf \\$(printf '%03o' $1); }

printf "%s\n" d_001_d  d_001_h  d_005_d  d_005_h  d_007_d  d_007_h | 
while read name; do 
  prefix=${name%%_*}
  suffix=${name##*_}
  [[ $name =~ ([0-9]+) ]] && num=$((96+10#${BASH_REMATCH[1]}))
  printf -v new_name "%s_%s_%s" $prefix $(chr $num) $suffix
  echo $new_name 
done

输出

d_a_d
d_a_h
d_e_d
d_e_h
d_g_d
d_g_h

chr功能礼貌this answer

答案 4 :(得分:1)

使用perl重命名工具,您可以使用正则表达式重命名:

rename -n 'y/[157]/[abc]/;s/00//' d_00?_?

d_001_d renamed as d_a_d
d_001_h renamed as d_a_h
d_005_d renamed as d_b_d
d_005_h renamed as d_b_h
d_007_d renamed as d_c_d
d_007_h renamed as d_c_h

如果使用-n(ot确实)的测试产生了良好的结果,则省略-n。