Operating System - HP-UX
1846621 Members
1523 Online
110256 Solutions
New Discussion

Re: insert text before first line

 
SOLVED
Go to solution
Anand_30
Regular Advisor

insert text before first line

Hi,

I am working on Sun OS. I need to enter a text before the first line in a file. How would i accomplish the task using sed.

Thanks,
Andy
6 REPLIES 6
Geoff Wild
Honored Contributor

Re: insert text before first line

sed -e '1i\ ' filename


Rgds...Geoff
Proverbs 3:5,6 Trust in the Lord with all your heart and lean not on your own understanding; in all your ways acknowledge him, and he will make all your paths straight.
Hein van den Heuvel
Honored Contributor

Re: insert text before first line


Isn't it a little more tricky to get the newline there?

sed -e '1i\^Jtest^J' file > newfile

In this example the ^J stands for a linefeed.
You can enter this on the command line with a control-V followed by control-J

Alternative using replace instead of insert:

sed '1s/^/test\^J/' file > newfile

Again ^J is entered as control-v followed by control-j and a \ is needed to escape that.


You may want to check out the "Handy one-liners for SED" file. For example the one attached to:
http://forums1.itrc.hp.com/service/forums/questionanswer.do?threadId=630972

hein.



Abdul Rahiman
Esteemed Contributor
Solution

Re: insert text before first line

Iam having fun with inserting ^v-^J ;-)
Or make use of a simple script,
# cat a.sed
1i\
mytext

# sed -f a.sed myfile > newfile

regds,
Abdul.
No unix, no fun
Hein van den Heuvel
Honored Contributor

Re: insert text before first line


I forgot to put in an obligatory perl alternative:

perl -e '@_=<>; print "test\n",@_' x

Here we tell perl to 'slurp' the input into an array @_, print the new line, and burp the array out again. This may be useful for more elaborated problems.

And just with the shell..

echo "test" > newfile; cat file >> newfile


Hein.

Hein van den Heuvel
Honored Contributor

Re: insert text before first line


[too bad we can not edit replies]


before someone else comments, yes I know 'slurpling' in perl is not efficient and does not scale well for large files.
Same goes for sed.
The more efficient processing for large files is just read and write in a loop.

perl -pe '$i++||print "test\n"' file > newfile


Hein.
Muthukumar_5
Honored Contributor

Re: insert text before first line

hai,

We can do it with sed as,
cat /input file/ | sed -e '1 s/^/\
/g' > netoutput file

or we can simply do it without sed using temporary files as,

cat input-file /tmp/testfile.log
echo "" > inputfile
cat /tmp/testfile.log >> inputfile

Regards,
Muthukumar.
Easy to suggest when don't know about the problem!