0 like 0 dislike
asked in Software by (4.8k points)

I need to replace a string in a lot of files in a folder in terminal. How can I do this?

linux replace string in all files

Your answer

pre, code


Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.

1 Answer

0 like 0 dislike
answered by (4.8k points)

Use sed - stream editor for filtering and transforming text:

sed -i 's/foo/bar/g' ./*

Occurrences of "foo" will be replaced with "bar".

Also you can use next commands:

find ./ -type f -exec sed -i 's/string1/string2/g' {} \;

Symbol / is not the delimiter in sed commands, it's just one of the possible ones. For this example, you can for example use, instead since it does not conflict with your strings:

echo 'I think http://www.site.loc/page is my favorite' | 
sed 's,http://www.site.loc/page,http://www.replace.loc/page,g'

Editor sed can take whatever follows the "s" as the separator. Since you are working with URL it is a good practice to use a different delimiter other than / to not confuse sed when your substitution ends and replacement begins.

However, having said that you can definitely use / if you wish too. You just need to escape the literal /.

So, you can either do:

sed 's/http:\/\/www.find.com\/page/http:\/\/www.replace.com\/page/g' input_file

or use a different delimiter to avoid making your cryptic sed more cryptic.

sed 's#http://www.site.loc/page#http://www.replace.loc/page#g' input_file


Related questions

0 like 0 dislike
1 answer 20 views
0 like 0 dislike
1 answer 21 views
0 like 0 dislike
1 answer 9 views
0 like 0 dislike
1 answer 17 views
0 like 0 dislike
1 answer 21 views
0 like 0 dislike
1 answer 23 views
0 like 0 dislike
1 answer 22 views