in Software by (9.4k points)
0 like 0 dislike

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

1 Answer

0 like 0 dislike
by (9.4k 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 is my favorite' | 
sed 's,,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:\/\/\/page/http:\/\/\/page/g' input_file

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

sed 's#' input_file


Your answer

Try to answer the question as detailed as possible.
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.