Results 1 to 5 of 5

Thread: Add character to beginning of line which do not match regexp

  1. #1
    Join Date
    Sep 2009
    Location
    England, UK
    Beans
    189
    Distro
    Xubuntu

    Add character to beginning of line which do not match regexp

    At the moment I'm trying to write a script that'll add a '#' to the beginning of each line from fcrontab. With the exception of lines which have the servicestatus or rotatelogs strings present.

    I know these are on the 1st and 2nd lines (but can't always guarentee they will be). So I've been looking at improving the block of code below to use regular expressions instead of line numbers.

    Does anyone have any suggestions?
    Code:
    #!/bin/bash
    
    FCRONTAB=/usr/bin/fcrontab
    FCRONTAB_TEMP=/root/fcron.tmp
    
    function disableCron() {
        $FCRONTAB -l > $FCRONTAB_TEMP
        sed -i '3,$ s/^/#/' $FCRONTAB_TEMP
        $FCRONTAB $FCRONTAB_TEMP
        rm $FCRONTAB_TEMP
    }
    
    disableCron

  2. #2
    Join Date
    Sep 2009
    Location
    England, UK
    Beans
    189
    Distro
    Xubuntu

    Re: Add character to beginning of line which do not match regexp

    So more Googling found a stackoverflow post that seems to do what I want.

    Although I can't seem to get it right
    Code:
    sed -i 's/\(.*servicestatus|rotatelogs*.\)/#\1/' $FCRONTAB_TEMP
    I know that's not going to ignore the lines I want (I'm just playing around atm).
    Last edited by deathadder; April 12th, 2011 at 01:56 PM.

  3. #3
    Join Date
    Feb 2007
    Location
    Romania
    Beans
    Hidden!

    Re: Add character to beginning of line which do not match regexp

    Code:
    sed '/servicestatus\|rotatelogs/! s/.*/# &/' file

  4. #4
    Join Date
    Sep 2009
    Location
    England, UK
    Beans
    189
    Distro
    Xubuntu

    Re: Add character to beginning of line which do not match regexp

    Fantastic! Thanks sisco311, to stop multiple #'s getting added to the line I changed it slightly to:
    Code:
    sed -i '/servicestatus\|rotatelogs/! s/^[^#]/# &/' $FCRONTAB_TEMP

  5. #5
    Join Date
    Apr 2010
    Beans
    88
    Distro
    Xubuntu 14.04 Trusty Tahr

    Re: Add character to beginning of line which do not match regexp

    A quick perl version if that helps:

    Code:
     
    #! /usr/bin/perl -w
    use strict;
     
    while (<>) {
            print "#" if ($_ !~ m/servicestatus|rotatelogs/);
            print;
    }
    Run as "script.perl filename"


    or as a 1 line command:

    Code:
     
    $ perl -p -e 'print "#" if ($_ !~ m/servicestatus|rotatelogs/)' filename

Tags for this Thread

Bookmarks

Posting Permissions

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