LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   shell script: insert line in a file (https://www.linuxquestions.org/questions/programming-9/shell-script-insert-line-in-a-file-618724/)

noir911 02-04-2008 08:36 PM

shell script: insert line in a file
 
I want to append to line number 45 of a file. Currently I am doing echo "something" >> file which puts "something" at the end of the file. But I would like to echo to, say, line number 33.

Thanks for any help.

BrianK 02-04-2008 08:38 PM

Quote:

Originally Posted by noir911 (Post 3046245)
I want to append to line number 45 of a file. Currently I am doing echo "something" >> file which puts "something" at the end of the file. But I would like to echo to, say, line number 33.

Thanks for any help.

sounds like homework, soooo....

what you need to do is separate the file into parts, output part 1 to a file, then the line to insert, then part 2 to the file.

head and tail can help, i.e. "head -n 10 myfile" will print out the first 10 lines of "myfile". "tail -n 10 myfile" will print out the last 10 lines of "myfile". "wc -l myfile" will count the number of lines in "myfile".

Hopefully that's enough to get you going. ;)

JWPurple 02-04-2008 09:00 PM

You could use awk - something like:

awk '{if(NR == 45) {print "new line" >>"myfile"}}'

(Not tested)

noir911 02-04-2008 10:15 PM

Quote:

Originally Posted by BrianK (Post 3046246)
sounds like homework, soooo....

what you need to do is separate the file into parts, output part 1 to a file, then the line to insert, then part 2 to the file.

head and tail can help, i.e. "head -n 10 myfile" will print out the first 10 lines of "myfile". "tail -n 10 myfile" will print out the last 10 lines of "myfile". "wc -l myfile" will count the number of lines in "myfile".

Hopefully that's enough to get you going. ;)

Sorry if you misunderstood but this is not homework - I needed to add some lines through a shell script to my squid config file.

noir911 02-04-2008 10:15 PM

Quote:

Originally Posted by JWPurple (Post 3046271)
You could use awk - something like:

awk '{if(NR == 45) {print "new line" >>"myfile"}}'

(Not tested)

Thanks!This helps. Good ol' awk.

ghostdog74 02-04-2008 10:29 PM

another way
Code:

# awk 'NR==45{print "newline"}1' file > outfile

angrybanana 02-04-2008 10:42 PM

sed way:
Code:

sed '45i\newline' file
use -i to edit in place redirect using '> outfile' to copy it to another file.
Also the backslash isn't necessary, I just put it there for clarity.
Code:

sed '45inewline' file
is the same thing.


All times are GMT -5. The time now is 05:51 PM.