Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux sed command does not change the target file

Tags:

regex

linux

sed

With my shell script, when I run ./Test1 hello result.

It is supposed to take hello as standard input and result as standard output. The shell should remove any whitespace before <td>, </td>, and abc

So, I write the script this way

tr -d [:blank:] < $1
grep -r "<td>" $1 | sed -r 's/<td>//g' > $2
sed -r 's/<\/td>//g' $2
sed -r 's/abc//g' $2

However, when I run this command, the content of result file is exactly the same as the content of hello file (the only difference is the whitespace is removed)

The file hello content:

<td>hello</td>
  <td>hello</td>
    <td>hello</td>
<td>abc</td>
 <td>abc</td>

How do I get sed to apply the change to the target file?

like image 736
user1988385 Avatar asked Jan 17 '13 20:01

user1988385


1 Answers

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.

like image 82
Chris Seymour Avatar answered Oct 16 '22 06:10

Chris Seymour