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;
.orig2
!!! (orig file is left intact, changes made to the new file)What is messing up sed
?
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.