You are not logged in.

#1 2009-03-01 03:53:14

tony5429
Member
Registered: 2006-03-28
Posts: 1,017

[SOLVED] How to Echo to a Specific Line of an Existing File?

I'd like to do something like...

echo "This is the new line 5." > file.txt(5)

where file.txt is an existing file. Does anyone know of a way to do this? If it can't be done via command-line, I'm okay with using C if someone knows how to do it in C...

Last edited by tony5429 (2009-03-01 04:56:31)

Offline

#2 2009-03-01 04:18:42

evr
Arch Linux f@h Team Member
Registered: 2009-01-23
Posts: 554

Re: [SOLVED] How to Echo to a Specific Line of an Existing File?

you could try using the insert functionality of the sed command

Offline

#3 2009-03-01 04:22:06

tony5429
Member
Registered: 2006-03-28
Posts: 1,017

Re: [SOLVED] How to Echo to a Specific Line of an Existing File?

Oh... How can I do that exactly?

Offline

#4 2009-03-01 04:40:09

B-Con
Member
From: USA
Registered: 2007-12-17
Posts: 554
Website

Re: [SOLVED] How to Echo to a Specific Line of an Existing File?

The lazy/inefficient way would be, to insert at line x, the following:

head file -n (x-1) > newfile
echo "my line" >> newfile
tail file -n +x >> newfile
mv newfile file

But if you don't really care about efficiency, it's simple and works.

Offline

#5 2009-03-01 04:54:28

tony5429
Member
Registered: 2006-03-28
Posts: 1,017

Re: [SOLVED] How to Echo to a Specific Line of an Existing File?

Thanks; this solution works for me. One minor item to point out, I had to use tail file -n +(x+1) >> newfile for the third line there.

Offline

#6 2009-03-01 04:57:54

evr
Arch Linux f@h Team Member
Registered: 2009-01-23
Posts: 554

Re: [SOLVED] How to Echo to a Specific Line of an Existing File?

edit: nevermind, i guess you already solved it smile

Last edited by evr (2009-03-01 05:00:06)

Offline

Board footer

Powered by FluxBB