Simpler Navigation for Servers and Operating Systems - Please Update Your Bookmarks
Completed: a much simpler Servers and Operating Systems section of the Community. We combined many of the older boards, so you won't have to click through so many levels to get at the information you need. Check the consolidated boards here as many sub-forums are now single boards.
If you have bookmarked forums or discussion boards in Servers and Operating Systems, we suggest you check and update them as needed.
cancel
Showing results for 
Search instead for 
Did you mean: 

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
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.
Sagar Sirdesai
Trusted Contributor

Re: insert # in a file

Hi rhansen,

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

Sagar