-1

Is there any way to search for a text string e.g Hello and replace it with e.g Hi in all the text files in a directory structure with MANY sub directories? I'm running Ubuntu 17.04 x64 server.

  • Is this MANY subdirectories contains files with string "Hello" ? And you want all strings to be replaced ? – Rooney Dec 8 '17 at 11:15
  • That is correct, I have about 450 000 files, in different subdirectories and I need to replace a few faulty links in them (about 8000 of them) – W.Scott7182 Dec 8 '17 at 11:26
3

You have to ssh into the remote machine and run the command described below.

The following command will replace all occurrences of "Hello" in all files inside a specific location (as per your choice) with "Hi".

find /path/to/main/parent/directory -type f -exec sed -i 's/hello/hi/gI' {} \;

Note

The above is case insensitive, if you want case sensitive replacement you can try with removing I, ie. 's/Hello/Hi/g'

/path/to/main/parent/directory : You must specify the parent directory from which your file containing string "Hello" starts.

for URLs

From the comment I came to know that you want to replace a URL with other which contains :// So please use the following method to replace strings which contains URL.

find /path/to/main/parent/directory -type f -exec sed -i 's,/URL1/,/URL2/,gI' {} \;
  • hmm... it seem's like it's finding the text strings however it itsn't replacing them with what I want. It returns this error: sed: -e expression #1, char 11: unknown option to `s' – W.Scott7182 Dec 8 '17 at 11:54
  • Oops, there is space before the {}, i missed it while pasting. I have corrected the command now. Try with adding space before {}. – Rooney Dec 8 '17 at 12:02
  • well I still get this <pre> sed: -e expression #1, char 11: unknown option to `s' </pre> maybe it is something I have to download? – W.Scott7182 Dec 8 '17 at 12:05
  • No, there is nothing you need to download. I believe there may be a typo in your command. Can you paste the command you are running ? – Rooney Dec 8 '17 at 12:09
  • find /var/www/html -type f -exec sed -i 's/twitter.com/VAMINyt/https://twitter.com/gI' {} \; – W.Scott7182 Dec 8 '17 at 12:20
1

Just another option using grep -Rl instead of find:

grep -Rl 'hello' /path/to/main/parent/directory | xargs -n1 sed -i 's|hello|hi|g'

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