Originally published at: https://www.cyberciti.biz/faq/how-to-use-sed-to-find-and-replace-text-in-files-in-linux-unix-shell/
I am a new Linux user. I wanted to find the text called “foo” and replaced to “bar” in the file named “hosts.txt.” How do I use the sed command to find and replace on Linux or UNIX-like system?
Hi there, I’m wondering why you use the -i flag without specifying a suffix/extension? The man page suggests this makes it useless to use -i.
Thanks for the explainer. I’m a very basic command line user so the level this is written at is good for me - I can make sense of almost all of it
The -i option passed to the sed command update file. a suffix/extension is optional. But you provide one a backup file will be created.
Need to search string1 (single line) and replace with string2 (multiple lines), I tried by changing the delimiter and using new line character \n but it not worked, it seems failing because of comma in the string. Your help would be appreciated.
String 1:
browsers: ['Chrome'],
String 2:
| browsers: ['Chrome', 'ChromeHeadless', 'MyHeadlessChrome'], > > customLaunchers: { > MyHeadlessChrome: { > base: 'ChromeHeadless', > flags: ['--disable-translate', '--disable-extensions' > } > },
Command I tried :
sed "s+browsers: ['Chrome']+browsers: ['Chrome', 'ChromeHeadless', 'MyHeadlessChrome'],\n customLaunchers: { \n MyHeadlessChrome: { \n base: 'ChromeHeadless', \n flags: ['--disable-translate', '--disable-extensions' \n } \n }+g" /tmp/try.js
Try escaping [
with \[
i.e.
sed "s/browsers: \['Chrome'\],/REPLACEMENT/' input
sed "s/browsers: \['Chrome'\],//' input
sed "s/browsers: \['Chrome'\],/browsers: ['Chrome', 'ChromeHeadless', 'MyHeadlessChrome'],\n>\n> customLaunchers: {/" input