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
450 views
in Technique[技术] by (71.8m points)

shell - How to use find and prename to reformat directory names recursively?

I am trying to find all directories that start with a year in brackets, such as this:

[1990] Nature Documentary

and then rename them removing brackets and inserting a dash in between.

1990 - Nature Documentary

The find command below seems to find the results, however I could not prefix the pattern with ^ to mark start of directory name otherwise its not returning hits.

I am pretty sure I need to use -exec or -execdir, but I am not sure how to store the found pattern and manipulate it.

find . -type d -name '[[[:digit:]][[:digit:]][[:digit:]][[:digit:]]] *'

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

1 Reply

0 votes
by (71.8m points)

With [p]rename:

-depth -exec prename -n 's/[(d{4})]([^/]+)$/$1 -$2/' {} +

Drop -n if the output looks good.

Without it, you'd need a shell script with several hardly intelligible parameter expansions there:

-depth -exec sh -c '
for dp; do
  yr=${dp##*/[} yr=${yr%%]*}
  echo mv "$dp" "${dp%/*}/$yr -${dp##*/[????]}"
done' sh {} +

Remove echo to apply changes.


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

...