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

regex - How do I find and replace a character when it is not one of the first 8 characters in the filename using prename?

This will for example recursively find and replace all hyphens in all filenames with a single space:

find . -type f -name "*-*" -execdir prename 's/-/ /g' "{}" ;

how would I modify this to only replace hyphens that are not within the first 8 characters of the file name.

question from:https://stackoverflow.com/questions/65517004/how-do-i-find-and-replace-a-character-when-it-is-not-one-of-the-first-8-characte

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

1 Reply

0 votes
by (71.8m points)

Pathnames passed to prename are prepended with ./ because of -execdir primary. So, you need to keep the first ten characters intact and substitute each dash with a space in the rest of the path string, which can be achieved fairly easily with a while loop (because g flag doesn't work when matches overlap) and PCRE's zero-width positive lookbehind assertion thingy*.

find -name '????????*-*' -type f -execdir prename -n '1 while s/.{10,}K-/ /' {} +

This invokes prename at least once for each directory, and thus, may be slow due to overhead from initialization. If that is a concern, you can use -exec instead of -execdir, and adjust the Perl expression accordingly. Below is my amateur attempt at it, use with caution.

-exec prename -n '/(.*/.{8})(.*)/; $_ = $1 . $2 =~ y/-/ /r' {} +

Drop -n if the output looks good.


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

...