1748267 Members
3801 Online
108760 Solutions
New Discussion юеВ

Re: insert # in a file

 
SOLVED
Go to solution
rhansen
Frequent Advisor

insert # in a file

Hello,

I have a text file that has hundreds of line. I need to comment out the first 150 lines by adding a "#".

Can someone let me know how do it in one shot.

Thanks.
10 REPLIES 10
Rita C Workman
Honored Contributor
Solution

Re: insert # in a file

How about

cat | sed s'/.*/#&/' >>

Rita
Rita C Workman
Honored Contributor

Re: insert # in a file

oops sorry ignored the 150 lines..

how about...

sed -n '1,150p' | sed s'/.*/#&/' >>

/Rita
Sagar Sirdesai
Trusted Contributor

Re: insert # in a file

sed '1,150s/^/#/' file > newfile
James R. Ferguson
Acclaimed Contributor

Re: insert # in a file

Hi:

If you prefer 'sed', Sagar's solution is good.

IF you want to use Perl and update the file in-place while preserving a backup copy as ".old", you could do:

# perl -pi.old -e '1..150 and s/^/#/' file

The GNU 'sed' also offers in in-place file update. HP's 'sed' does not.

Regards!

...JRF...
Steven Schweda
Honored Contributor

Re: insert # in a file

> [...] update the file in-place [...]

Of course, if you'd like to check the work
before replacing the original file, then
in-place may not be the ideal method to use.
Dennis Handly
Acclaimed Contributor

Re: insert # in a file

>I need to comment out the first 150 lines by adding a "#".

If you are only doing it once, you can use vi, similar to Sagar's sed:
:1,150s/^/#/
Viktor Balogh
Honored Contributor

Re: insert # in a file

here is a solution with awk:

awk '{if (NR < 151) print "#"$0; else print $0}' filename

****
Unix operates with beer.
T. M. Louah
Esteemed Contributor

Re: insert # in a file

Great tips, thx
Little learning is dangerous!
rhansen
Frequent Advisor

Re: insert # in a file

Thanks for the replies.