-1

Given a main directory called FOOwith many sub-directories in there, I would like to go to each sub-directory, find the path:

/mango/pears/peanuts/butter/ 

Replace /mango/pears with /supplier

I understand sed is what I am looking for but I can't figure it out:

cd /FOO
sed -i 's|/mango/pears|/supplier|g' $(find . -type f)

Any thoughts? This question does not seek to rename files as in this

code123
  • 2,082
  • 4
  • 30
  • 53
  • Possible duplicate of [Finding multiple files recursively and renaming in linux](https://stackoverflow.com/q/16541582/608639), [Recursively renaming folders and files](https://stackoverflow.com/q/35084642/608639), [Rename files in multiple directories to the name of the directory](https://stackoverflow.com/q/14306117/608639), etc. – jww Mar 28 '18 at 17:53
  • @rkta this worked for me after asking the question `find . -type f -exec perl -pi -e 's|/mango/pears|/supplier|g' {} \;`. However, it has to query all file types in sub-folders. My target files are `.sh`. This is no duplicate question to any of the above. – code123 Mar 28 '18 at 18:06
  • Are you trying to move files or do you just want a modified list of names, based on the output of find? Sed -i will work on the files, find finds, not on their names, or do the files contain their names/path? – user unknown Mar 29 '18 at 11:37

1 Answers1

1

To find every path in FOO, which contains /mango/pears/peanuts/butter/, you would use:

find /FOO -path "*/mango/pears/peanuts/butter/*"

If you want to modify the result list, you would pipe the output through sed (but without -i, which only makes sense with files to change in place):

find /FOO -path "*/mango/pears/peanuts/butter/*" -type f | sed 's|/mango/pears|/supplier|g' 

Sed -i works on each result of sed, but would change such paths inside the files. This could work for your command, but is vulnerable to white space in filenames. Instead, you should use the -exec parameter:

find /FOO -path "*/mango/pears/peanuts/butter/*" -type f -exec sed -i  's|/mango/pears|/supplier|g' {} ";"
user unknown
  • 35,537
  • 11
  • 75
  • 121
  • thanks for the detailed solution. what if I want to change path in `.sh` files only without touching `.nc4` and other files? – code123 Mar 29 '18 at 15:09
  • You would append the parameter ` -name "*.sh" ` behind "-type f" and before "-exec ..." - be careful! The order of params can have and often has influence on the find command. Read the manpage before testing, test and make backups of sensible data before testing. But with time, find will be one of your fastest and mightiest tools. – user unknown Mar 29 '18 at 17:14