0

I am trying to use sed to replace a string with another one. I used the below command and it worked just fine up until I ran cat index.html and it went back to the old string. Can someone help, please?

<h1>
Hello World
</h1>
<p>This is out first WebDev study</p>
</body>
</html>
$ sed 's/Hello World/About Us/' index.html
<!DOCTYPE>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>
About Us
</h1>
<p>This is out first WebDav study</p>
</body>
</html>
$ cat index.html
<!DOCTYPE>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>
Hello World
</h1>
<p>This is out first WebDav study</p>
</body>
</html>
Roman Riabenko
  • 2,145
  • 3
  • 15
  • 39
Murad M
  • 13
  • 1
  • sed by default writes the modified file to standard output - see [How can I get my sed command to make permanent changes to a file?](https://unix.stackexchange.com/a/95886/65304) for how to write the modified content back to the input file (aka "in-place" editing) – steeldriver Aug 11 '21 at 23:14
  • 1
    Also note that while sed can work for extremely simple cases like this, you really should use a HTML parser if you want to extract or modify HTML files (this typically means using another language, like perl or python, or a tool like `xmlstarlet` if your html is valid xhtml). e.g. your sed script would fail if there was a linefeed or more than one space (or a `` between `Hello` and `World` (but would still render exactly the same in a browser. sed is a line-oriented tool, it does not deal well with structured text. HTML is not a line-oriented format, it is structured text. – cas Aug 12 '21 at 07:24
  • 1
    Does this answer your question? [How can I get my sed command to make permanent changes to a file?](https://unix.stackexchange.com/questions/95884/how-can-i-get-my-sed-command-to-make-permanent-changes-to-a-file) – G-Man Says 'Reinstate Monica' May 15 '22 at 18:33

1 Answers1

2

From the man page:

-i[SUFFIX], --in-place[=SUFFIX]
     edit files in place (makes backup if SUFFIX is supplied)

So, in your case you just need to add the flag:

sed -i 's/Hello World/About Us/' index.html
user1794469
  • 3,909
  • 1
  • 23
  • 42