Showing results for 
Search instead for 
Do you mean 

insert # in a file

SOLVED
Go to Solution
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
Honored Contributor Honored Contributor

Re: insert # in a file

How about

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

Rita
Honored Contributor Honored Contributor

Re: insert # in a file

oops sorry ignored the 150 lines..

how about...

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

/Rita
Trusted Contributor Trusted Contributor

Re: insert # in a file

sed '1,150s/^/#/' file > newfile
Acclaimed Contributor 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...
Honored Contributor 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.
Acclaimed Contributor 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/^/#/
Honored Contributor 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.
Esteemed Contributor Esteemed Contributor

Re: insert # in a file

Great tips, thx
Little learning is dangerous!
Frequent Advisor

Re: insert # in a file

Thanks for the replies.
Trusted Contributor Trusted Contributor

Re: insert # in a file

Hi rhansen,

I hope we deserve some for our answers.
We encourge you to assign points

Sagar