Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

regex - matching and reformatting poorly typed filenames

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...