Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a line at specific line number with sed or awk

Tags:

sed

awk

I have a script file which I need to modify with another script to insert a text at the 8th line.

String to insert: Project_Name=sowstest, into a file called start.

I tried to use awk and sed, but my command is getting garbled.

like image 339
ashok Avatar asked Jun 30 '11 15:06

ashok


People also ask

How do you use sed on a specific line?

Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.

How do I add a new line in awk?

Original answer: Append printf "\n" at the end of each awk action {} . printf "\n" will print a newline.

How do I go to a specific line number in Linux?

To do this, press Esc , type the line number, and then press Shift-g . If you press Esc and then Shift-g without specifying a line number, it will take you to the last line in the file.


2 Answers

sed -i '8i This is Line 8' FILE 

inserts at line 8

This is Line 8 

into file FILE

-i does the modification directly to file FILE, no output to stdout, as mentioned in the comments by glenn jackman.

like image 85
user unknown Avatar answered Sep 21 '22 21:09

user unknown


An ed answer

ed file << END 8i Project_Name=sowstest . w q END 

. on its own line ends input mode; w writes; q quits. GNU ed has a wq command to save and quit, but old ed's don't.

Further reading: https://gnu.org/software/ed/manual/ed_manual.html

like image 38
glenn jackman Avatar answered Sep 21 '22 21:09

glenn jackman