Operating System - HP-UX
1833883 Members
1667 Online
110063 Solutions
New Discussion

Re: how to add one line at the top of a file

 
SOLVED
Go to solution
Hanry Zhou
Super Advisor

how to add one line at the top of a file

thanks,
none
9 REPLIES 9
Patrick Wallek
Honored Contributor

Re: how to add one line at the top of a file

Where are you trying to accomplish this? Within vi? Or using ed, sed, awk....?

If it is just within vi, you can do a -O (that is hold down shift and hit the letter O) while you are at the top of the file.

Hanry Zhou
Super Advisor

Re: how to add one line at the top of a file

please using command line.
none
Fragon
Trusted Contributor

Re: how to add one line at the top of a file

Use a shell scritp to do this:
=======================
#more addtotop
echo $1 >$$.tmp
cat $2 >>$$.tmp
cat $$.tmp >$2
rm $$.tmp
=======================
On how to use:
#addtotop "The string you want to add to the first line." FILENAME

Good luck!

Michael Tully
Honored Contributor

Re: how to add one line at the top of a file

You actually get it doing this:

cat myfile | sed '1 s/^/\controlvcontrolj/'

it will appear on the screen as this:

cat myfile | sed '1 s/^/\^J/'

HTH
Michael
Anyone for a Mutiny ?
Hanry Zhou
Super Advisor

Re: how to add one line at the top of a file

I did not make myself clear.

Here is what I want to achieve.

I have a few lines coming from a output:
line1
line2
line3
and I want to add these lines
on the top of a file, myfile.

none
Michael Tully
Honored Contributor

Re: how to add one line at the top of a file

How about this:

e.g.

# cat /tmp/wrk1
line1
line2
line3
# cat /tmp/wrk2
file1
file2
file3


# head -n 3 /tmp/wrk1 >/tmp/wrk3 ; cat /tmp/wrk2 >>/tmp/wrk3
# cat /tmp/wrk3
line1
line2
line3
file1
file2
file3
Anyone for a Mutiny ?
MANOJ SRIVASTAVA
Honored Contributor

Re: how to add one line at the top of a file

Hi Roger


If u get line1
line2
line3 ina file say test then you can jsut

do

cat test >file
and then
cat myfile >> file


Manoj Srivastava
Dietmar Konermann
Honored Contributor

Re: how to add one line at the top of a file

The is no efficient way to grow a file by inserting contents. You can only overwrite or append something... and you can truncate the file from the end.

So all solutions include unfortunately a complete and inefficient copy operation. See suggestions above and pick the one you like.
"Logic is the beginning of wisdom; not the end." -- Spock (Star Trek VI: The Undiscovered Country)
Jean-Luc Oudart
Honored Contributor
Solution

Re: how to add one line at the top of a file

take 1st 3 lines of file1 and insert them on top of file 2 :
( head -n3 f1 && cat f2) >> f3
file f3 is the result

Jean-Luc
fiat lux