1

Background

I am new to linux/unix (I'm on a mac. Don't know which I am using), but someone made a lot of folders and files under the wrong name, and I need to go in and replace everything with the correct name. E.g. she named it apple instead of orange.

What I need to do

I navigated to the directory of interest, and within that directory, I need to:

  1. Replace the word apple with orange in the name of any subfolder or file or directory

  2. Replace the word apple with orange within any files (both text and non-text)

What I have tried

I tried this command:

grep -lr "apple" . | xargs sed -i "s/apple/orange/g"

and that didn't work at all

I also tried :

find ./ -exec sed -i 's/apple/orange/g' {} \;

This replaced a lot of the instances, but not all. And it does not replace the word within file/folder/directory names

Please help!

  • Just a guess: mac comes with bsd-sed (without -i option); often gnu seg is available with the name gsed, gnused, or you install it... – JJoao Sep 20 '16 at 17:05
  • both of your examples only work on the contents of a file. to rename files, you will need a separate command. you will want to use find to get all files with apple in the name, then for each of those files, use mv to rename the file changing apple to orange. – MikeA Sep 20 '16 at 20:43
  • Thank you, MikeA! I was hoping there was a shortcut so I could rename all the files at once. Glad either way to know what to do. – JLynn Sep 21 '16 at 14:34
0

This might be more BASHy then is possible, but maybe it will help toward the right direction.

In short, find all the folders with apple, reverse the sort so that

/tmp/apple/test/apple

doesn't cause trouble when the first "apple" is changed out of order. Next feed the output into a while loop with the read function loading up a variable that holds all the folders that match. Finally, mv the folders into the right name structure.

for directories, try

find ./ -regex '^.*apple' -type d | sort -r | while read badname ; do mv $badname ${badname/%apple/orange}; done

for file names, (after directories are cleaned up )

find ./ -regex '^.apple.' -type f | sort -r | while read badname ; do mv $badname ${badname/apple/orange}; done

for file content there are many other examples of that,

Awk/Sed: How to do a recursive find/replace of a string?

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.