-1

I have a large number of filenames that have been poorly formatted, which I would like to clean up. The idea is to reformat the names so that they are more sensible.

Here are some examples:

01harpharm_3.1.aiff 1
01harpmute_2.6.aiff 1
01harpmute_2.6.aiff 2
01harpmute_2.6.aiff 3
01harpmute_2.6.aiff 4

If we look at the last example, the goal would be to rewrite

01harpmute_2.6.aiff 4 as 01harpmute_2.6.4.aiff.

I would like to use bash for this, either via a script (for loop), find, rename, or a combination thereof. Would anyone have opinions on how to best tackle this?

1 Answer 1

1

Could you please try following once. Following will only print the rename commands on screen, you could run 1 command from it and if you are happy with results then you could run my 2nd code.

find . -type f -name "*.aiff*" -print0 | 
while IFS= read -r -d '' file
do
  echo "$file" | 
  awk '
    BEGIN{ s1="\"" }
    { val=$0; sub(/^\.\//,""); sub(/\.aiff/,"."$2"&",$1)
      print "mv " s1 val s1 OFS $1
    }'
done

OR in case you want to put condition and check if file name has space or not so put an additional condition in awk command it will skip files which are not having space in their names.

find . -type f -name "*.aiff*" -print0 | 
while IFS= read -r -d '' file
do
  echo "$file" | 
  awk '
    BEGIN{ s1="\"" }
    NF==2{ val=$0; sub(/^\.\//,""); sub(/\.aiff/,"."$2"&",$1)
      print "mv " s1 val s1 OFS $1
    }'
done


Run following only after you have tested above code successfully please.

find . -type f -name "*.aiff*" -print0 | 
while IFS= read -r -d '' file
do
  echo "$file" | 
  awk '
    BEGIN{ s1="\"" }
    { val=$0; sub(/^\.\//,""); sub(/\.aiff/,"."$2"&",$1)
      print "mv " s1 val s1 OFS $1
    }' | sh
done
8
  • This works a treat! Thank you, @RavinderSingh13 - If I want to change the extension for a subset of the files, can I just alter sub(/\.aiff/,"."$2"&",$1) to be sub(/\.newext/,"."$2"&",$1) ?
    – jml
    Commented Nov 26, 2019 at 3:48
  • 1
    @jml, Your welcome, yes you could give it a try should work. Also you could select this answer as a correct answer too, cheers. Commented Nov 26, 2019 at 3:51
  • 1
    absolutely - sorry for the delay; just got back to this project.
    – jml
    Commented Nov 26, 2019 at 3:52
  • 1
    @jml, Yes sed is older tech than awk. awk definitely have upper hand than sed, and with time it is evolving too, so you can learn it and it will help you through out your life trust me on that :) Commented Nov 26, 2019 at 4:12
  • 1
    I saw this as well: stackoverflow.com/questions/1632113/…
    – jml
    Commented Nov 26, 2019 at 7:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.