Question Details

No question body available.

Tags

awk sed

Answers (4)

Accepted Answer Available
Accepted Answer
May 28, 2025 Score: 3 Rep: 209,042 Quality: High Completeness: 70%

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.

May 28, 2025 Score: 3 Rep: 12,797 Quality: Medium Completeness: 100%

Either Perl or awk are better tools for this task. For example, use this Perl one-liner:

perl -i.bak -ne 'print "line1 data\nline2 data\nline3 data\n" if $. == 1; next if 1..3; print;' file.txt

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.
-i.bak : Edit input files in-place (overwrite the input file). Before overwriting, save a backup copy of the original file by appending to its name the extension .bak. If you want to skip writing a backup file, just use -i and skip the extension.

$. : Current input line number.
next if 1..3; print; : skip a line if line number is between 1 and 3, inclusive. Otherwise, print the line.

See also:

May 29, 2025 Score: 1 Rep: 59,363 Quality: Low Completeness: 40%

This might work for you (GNU sed):

sed -i.bak '1,3c\line1\nline2\nline3' file

Change lines 1 to 3 and make a backup of the original file in file.bak.

Alternatively use:

sed -i.bak '1,3c\
line1\
line2\
line3' file

Where you place a \ at the end of each line after the c command to represent a newline.

May 29, 2025 Score: 0 Rep: 38,342 Quality: Low Completeness: 70%

You might exploit GNU sed for this task following way, let file.txt content be

Able
Baker
Charlie
Dog
Easy

then

sed '1,3d;4i uno\ndos\ntres' file.txt

gives output

uno
dos
tres
Dog
Easy

Explanation: I instruct GNU sed that for lines 1,3 (inclusive,inclusive) it should delete than and for 4th line it should insert provided text before that line. Observe that there is not trailing newline character, as it will be added by GNU sed. If you want to know more about i command then read sed commands summary.

(tested in GNU sed 4.9)