user1256539
user1256539

Reputation:

Rename folder name in bash

I need to rename the following folders:

d_001_d  
d_001_h  
d_005_d  
d_005_h  
d_007_d  
d_007_h  

In:

d_a_d  
d_a_h  
d_b_d  
d_b_h  
d_c_d  
d_c_h  

So basically each code number correspond to a name(letter). I tried with the sed command and a for loop with an array but I'm not able to get exactly what I want.

Thanks for help

Upvotes: 0

Views: 4609

Answers (5)

user unknown
user unknown

Reputation: 36229

With the perl rename tool you can rename with regex:

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

Omit the -n if the test with -n(ot really) yields a fine result.

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246807

Without hardcoding the number->char mappings:

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

outputs

d_a_d
d_a_h
d_e_d
d_e_h
d_g_d
d_g_h

chr function courtesy this answer

Upvotes: 1

dank.game
dank.game

Reputation: 4719

If the directory names are all the same length, you can use this:

#!/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

Upvotes: 1

bos
bos

Reputation: 6535

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

Upvotes: 3

kev
kev

Reputation: 161674

$ 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

Upvotes: 1

Related Questions