Find the answer to your Linux question:
Results 1 to 6 of 6
Like Tree2Likes
  • 1 Post By Irithori
  • 1 Post By marion50
Dears, Does sed or other command edit the 1st line and comments it? Meaning adds "#" to the first line in a file for example? Summary: Insert # to the ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Dec 2010
    Posts
    8

    Adding # to the first line


    Dears,

    Does sed or other command edit the 1st line and comments it? Meaning adds "#" to the first line in a file for example?

    Summary: Insert # to the first line.

    Before: Comment me please.
    sed command or another command

    After: #Comment me please.

    ------And if possible a way to remove the "#" using command line.

    Thanks.

  2. #2
    Trusted Penguin Irithori's Avatar
    Join Date
    May 2009
    Location
    Munich
    Posts
    3,398
    Code:
    sed  '1s/\(.*\)/#\1/' <FILE>
    Deleting the # is left as a exercise
    You must always face the curtain with a bow.

  3. #3
    Just Joined!
    Join Date
    Dec 2010
    Posts
    8
    Quote Originally Posted by Irithori View Post
    Code:
    sed  '1s/\(.*\)/#\1/' <FILE>
    Deleting the # is left as a exercise
    it throws the correct output but doesn't save the file.

  4. #4
    Trusted Penguin Irithori's Avatar
    Join Date
    May 2009
    Location
    Munich
    Posts
    3,398
    If you verified the output, then use the -i flag.
    sed will then edit in-place.
    leblinux likes this.
    You must always face the curtain with a bow.

  5. #5
    Just Joined!
    Join Date
    Apr 2011
    Posts
    2
    Quote Originally Posted by leblinux View Post
    Dears,

    Does sed or other command edit the 1st line and comments it? Meaning adds "#" to the first line in a file for example?

    Summary: Insert # to the first line.

    Before: Comment me please.
    sed command or another command

    After: #Comment me please.

    ------And if possible a way to remove the "#" using command line.

    Thanks.
    To insert as asked do

    sed -i "1s/^/#/" FILE

    where 1 is the 1st line and ^ is the first character of line

    To remove the first # of the 1st line do

    sed -i "1s/#//" FILE
    leblinux likes this.

  6. #6
    Trusted Penguin Irithori's Avatar
    Join Date
    May 2009
    Location
    Munich
    Posts
    3,398
    That is faster and simpler. Nice

    Nitpicker: The remove expression should check for the start of the line, aka: "1s/^#//"
    Or better yet: optional tabs/whitespaces before the # : "1s/^\([ \t]\)*#//"
    Last edited by Irithori; 06-24-2011 at 10:00 AM.
    You must always face the curtain with a bow.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •