0

I am new to using Bash scripting, but I have discovered a few solutions that use it to either remove or rename the filename for files within directories and sub-directories in Ubuntu 16.04. For example, my file structure is shown below. So, the FolderFruit,,, is the filename of our main directories. SubFolderApple???. SubFolder!!!Kiwi and SubFolder_Food_Banana are the filenames of our subdirectories. ListAppleFood, ListKiwiFood, and ListBanana are the filename of our individual files.

>FolderFruit,,,
>>   SubFolderApple??
>>>      ListAppleFood.txt
>>   SubFolder!!Kiwi
>>>      ListKiwiFood.pdf
>>   SubFolder_Food_Banana
>>>      ListBanana.csv

The goal is to change the filenames above into as shown below by removing any punctuation (e.g., ? and !) and the string 'Food' that appear among those filenames.

>FolderFruit
>>   SubFolderApple
>>>      ListApple.txt
>>   SubFolderKiwi
>>>      ListKiwi.pdf
>>   SubFolderBanana
>>>      ListBanana.csv

So far, I manage to script it as below, but it is not working. Thus, I would like to get help from any experienced Bash or Linux users.

shopt -s globstar for f in ./**; do sed 's/\([[:punct:]]\)/\\\1/g' "$f" done
  • I don't see any mv command here... – FedonKadifeli Sep 11 '20 at 8:48
2

Instead of using a for loop you could use find with -execdir:

$ find -depth -mindepth 1 -type f,d -execdir \
  rename 's/((Sub)?Folder|Food|List|[_,!?])//g' {} \;

If I would elaborate on the comment, rename does not make any distinction between files and directories which makes it exponentially more difficult (to preserve the .ext). In this case, I believe it's better to split the process into two steps and process files and directories separately.

$ find -mindepth 1 -depth \
   \( -type f -execdir rename 's/(List|Food|[[:punct:]])(?![^.]*$)//g' {} \; \) \
-o \( -type d -execdir rename 's/((Sub)?Folder|Food|[[:punct:]])//g' {} \; \)

The two command does basically the same thing except for the second one can handle dots.

  • Thanks, @bacOn for your advice. I will try your script soon. Could you advice me on the coding part on how to remove the specific string 'Food' as well in the filenames for files, subdirectories, and directories, please? – kjyon2 Sep 12 '20 at 1:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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