awksed

sed delete and replace on top of file is not working as expected


I want to replace top 3 lines of my file. For this task, these two commands work fine, but then I get two .bak (saved) files...

These work:

sed -i.orig1 '1,3d' /my/path/file;

sed -i.orig2 '1s/^/line1 data\nline2 data\nline3 data\n/' /my/path/file;

But this command fails:

sed -i.orig2 '1,3d;1s/^/line1 data\nline2 data\nline3 data\n/' /my/path/file;
  1. adds 3 lines.
  2. modified filename is .orig2 !!! (orig file is left intact, changes made to the new file)
  3. 3 top lines were not deleted in the new file (where 3 new lines were added)

What is messing up sed?


Solution

  • Keep it simple and just use awk, e.g. using GNU awk for "inplace" editing:

    awk -i inplace 'NR==1{ print "line1 data\nline2 data\nline3 data" } NR>3' file
    

    That's doing literal string printing so where your sed command would fail if line1 data contained any backreference metachars such as & or \1, the awk command would succeed and simply print it as-is. See Is it possible to escape regex metacharacters reliably with sed for more information on escaping regexp and backreference metachars in sed commands.