Operating System - HP-UX
1754285 Members
3312 Online
108813 Solutions
New Discussion юеВ

Shell script: put some text in the first line

 
SOLVED
Go to solution
Sharvil Desai
Frequent Advisor

Shell script: put some text in the first line

Can anyone please tell me what is the best way to add some text to the first line of a file that already exists and has lots of lines? Thank you!
"help!"
10 REPLIES 10
Pete Randall
Outstanding Contributor

Re: Shell script: put some text in the first line

There's most likely a better way but this would certainly work:

echo "text" > file.new
cat file >> file.new
mv file.new file


Pete

Pete
Sharvil Desai
Frequent Advisor

Re: Shell script: put some text in the first line

That would work, but I am hoping that someone can think of a better way. If noone can come up with a way then I will gladly accept your answer and assign points. Thank you.
"help!"
Sharvil Desai
Frequent Advisor

Re: Shell script: put some text in the first line

That would work, but I am hoping that someone can think of a better way. If noone can come up with a better way then I will gladly accept your answer and assign points. Thank you.
"help!"
Hai Nguyen_1
Honored Contributor

Re: Shell script: put some text in the first line

Sharvil,

Try this:

# echo "new first line text here" | cat - yourfile | tee yourfile

Hai
Hai Nguyen_1
Honored Contributor
Solution

Re: Shell script: put some text in the first line

Sharvil,

if you want to suppress the ouptput from the above command, then try this:

# echo "new first line text here" | cat - yourfile | tee yourfile >/dev/null

Hai
Sharvil Desai
Frequent Advisor

Re: Shell script: put some text in the first line

Thank you both!
I like Hai Nguyen's answer.
Everyone gets points!
"help!"
James R. Ferguson
Acclaimed Contributor

Re: Shell script: put some text in the first line

Hi:

If you like:

# awk 'BEGIN{print "INSERTED_TEXT!"};{print $0}' filename > filename.new
# mv filename.new filename

Regards!

...JRF...
Chris Vail
Honored Contributor

Re: Shell script: put some text in the first line

Just use vi, or your favorite text editor.
If you're not familiar with vi, here's a quick primer:
vi filename
O (thats capital "O", not zero) to "open" the first line.
Type your text.
:wq (thats the key, followed by the colon, then the w (write) then q (quit). You're done.


Chris
Curtis Larson_2
Advisor

Re: Shell script: put some text in the first line

it does depend on where you want to add your text, beginning, end, somewhere in the middle.

you can use sed, awk, ex. to do this.

file.tmp
mv file.tmp file
use a for appending text
i for insert text at the begining
s for subtitution, or changes somewhere in the middle