Linux sed command does not change the target file

If you want to store the changes from sed back to the file use the -i option:

$ cat file
<head>abc</head>
    <td>hello</td>
      <td>hello</td>
        <td>hello</td>
    <td>abc</td>
     <td>abc</td>
<h1>abc</h1>

$ sed -ni '/<td>/{s/^\s*//;s/abc//;s/<\/\?td>//g;p}' file

$ cat file
hello
hello
hello

Edit: The regexp is clearer if we use a different separator with sed and use the extended regexp option -r:

$ sed -r 's_</?td>__g' file
    hello
      hello
        hello
    abc
     abc

The ? make the previous character optional so the / doesn't have to be present making the regexp match <td> and </td> in one.


In sed command Use the -i option in order to change file itself, if not, the output printed on the screen but the file stays the same.

The formula would be:

sed -i <targetFile> 's/<beforeText>/<afterText>/g' <targetFile>

For example:

sed -i myCredentials.txt 's/secretPassword/xxx/g' myCredentials.txt

Another option - output to another file and rename it:

sed 's/secretPassword/xxx/g' myCredentials.txt > temp.txt
rm myCredentials.txt && mv temp.txt myCredentials.txt

for more info, look at the documentation:

The sed utility reads the specified files, or the standard input if no files are specified, modifying the input as specified by a list of com- mands. The input is then written to the standard output. A single command may be specified as the first argument to sed. Multiple commands may be specified by using the -e or -f options. All commands are applied to the input in the order they are specified regardless of their origin.

-i Edit files in-place, saving backups with the specified extension. If a zero-length extension is given, no backup will be saved. It is not recommended to give a zero-length extension when in-place editing files, as you risk corruption or partial content in situ- ations where disk space is exhausted, etc.

Tags:

Linux

Regex

Sed