bash - Rename folder with name consisting of multiple words -
for begining have such script:
#!/bin/bash in *; if [ -d "$i" ]; if [ "$i" == $(grep $i names.txt | cut -d ' ' -f 1) ]; mv $i $(grep $i names.txt | cut -d ' ' -f 2) else echo "the word $i wasn't found in dictionary" fi fi done
which renames files dictionary (names.txt) line of pattern "english_word german_one".
one eins 2 zwei mein dein
the problem is: works files names one-wordish. "one" becomes "eins", "two" becomes "zwei", "one two" doesn't become "eins zwei". how rename files names consisting more 1 word, e.g "my documents", "first folder", etc? know must somehow tokenize folder name, don't how. new bash. in advance.
here's pure bash solution rather general: we'll tokenize folder name , perform translation on each word found in name. before that, we'll load dictionary hash array:
#!/bin/bash # load dictionary declare -a dictionary=() while read -r eng ger; [[ $eng ]] && [[ $ger ]] || continue dictionary[$eng]=$ger done < dictionary_file tokenize() { # split $1 2 arrays: # tokenize_sep consists of non-alpha strings # tokenize_alpha consists of alpha strings # have: $1=${tokenize_sep[0]}${tokenize_alpha[0]}${tokenize_sep[1]}${tokenize_alpha[1]} ... local var=$1 tokenize_sep=() tokenize_alpha=() while [[ $var ]]; [[ $var =~ ([^[:alpha:]]*)(.*) ]] tokenize_sep+=( "${bash_rematch[1]}" ) var=${bash_rematch[2]} [[ $var =~ ([[:alpha:]]*)(.*) ]] tokenize_alpha+=( "${bash_rematch[1]}" ) var=${bash_rematch[2]} done } translate_ary() { # translates each word given arguments according hash array dictionary # returned array translate_ary_ret local w t translate_ary_ret=() w; if [[ $w ]]; t=${dictionary[$w]} [[ $t ]] || t=$w else t= fi translate_ary_ret+=( $t ) done } intertwine() { # $1 , $2 2 array names # returns string intertwine_ret consists of fields of $1 , $2 intertwined (shuffled) local ary1=$1[@] ary2=$2[@] ary1=( "${!ary1}" ) ary2=( "${!ary2}" ) intertwine_ret= for((i=0;i<${#ary1[@]};++i)); intertwine_ret+=${ary1[i]}${ary2[i]} done } translate() { # translates string given in $1, preserving separators # return string in translate_ret tokenize "$1" translate_ary "${tokenize_alpha[@]}" intertwine tokenize_sep translate_ary_ret translate_ret=$intertwine_ret } # renaming: in *; translate "$i" [[ $i = "$translate_ret" ]] && continue echo mv -nv -- "$i" "$translate_ret" done
it's not one-liner, should job.
i called script banana
, chmod +x
and:
$ ls -1 banana banana_is_my_favorite_fruit dictionary_file --one..my^ your-banana.one one_two_bananas your_two...pdf $ ./banana mv -nv -- banana_is_my_favorite_fruit banana_is_mein_favorite_fruit mv -nv -- --one..my^ your-banana.one --eins..mein^ dein-banana.eins mv -nv -- one_two_bananas eins_zwei_bananas mv -nv -- your_two...pdf dein_zwei...pdf
nothing has been moved: this, remove echo
in front of mv
command @ bottom of script.
Comments
Post a Comment