Linux recursively replace periods for all directorys and all but last period for files with underscores

匆匆过客 提交于 2021-02-10 15:13:57

问题


I have the following command which recursively renames all the files/directory's to lowercase and replaces spaces with _.

find . -iname "*" |  rename 'y/A-Z/a-z/; s/ /_/g;'

How do I extend it to remove all periods from directories and leave just the last period for files?

So input would be: this.is.a.directory this.is.a.file.txt

Output this_is_a_directory this_is_a_file.txt


回答1:


You can do this using find in a while loop and using a regex to leave last DOT for files:

while IFS= read -rd '' entry; do
   entry="${entry#./}"         # strip ./
   if [[ -d $entry ]]; then
      rename 'y/A-Z/a-z/; s/ /_/g; s/\./_/g' "$entry"
   else
      rename 'y/A-Z/a-z/; s/ /_/g; s/\.(?=.*\.)/_/g' "$entry"
   fi
done < <(find . -iname '*' -print0)

s/\.(?=.*\.)/_/g will only replace a DOT if there is another DOT ahead in the input.



来源:https://stackoverflow.com/questions/43146061/linux-recursively-replace-periods-for-all-directorys-and-all-but-last-period-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!