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.
Asked
Active
Viewed 3,442 times
-1

Zanna
- 70,465

W.Scott7182
- 1
- 1
- 3
2 Answers
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 08 '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 08 '17 at 12:02 -
well I still get this
sed: -e expression #1, char 11: unknown option to `s'
maybe it is something I have to download? – W.Scott7182 Dec 08 '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 08 '17 at 12:09
-
find /var/www/html -type f -exec sed -i 's/https://twitter.com/VAMINyt/https://twitter.com/gI' {} ; – W.Scott7182 Dec 08 '17 at 12:20
-
you need to escape the slashes in your search and replace terms with a backslash OR use a different separator (currently
/
) for sed that is not within your search term, e.g.|
==>sed -i 's|hello|hi|gI'
– pLumo Dec 08 '17 at 12:31 -
@W.Scott7182, the
sed
got confused with//
in your twitter URL, thats why the error occurred, i have edited the answer by adding command to replace strings containing//
– Rooney Dec 08 '17 at 12:35 -
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'

pLumo
- 26,947
MANY subdirectories
contains files with string "Hello" ? And you want all strings to be replaced ? – Rooney Dec 08 '17 at 11:15