Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

sed multi-line replace

  • 08-06-2011 10:34AM
    #1
    Registered Users, Registered Users 2 Posts: 6,762 ✭✭✭


    Can anyone point me in the right direction for this please?

    I'm trying to find and replace multiple lines of text in a file and can't figure out how to do it with sed/awk.

    I'm trying to enable bash-completion for all users, so editing the /etc/bash.bashrc file on a Ubuntu system.

    I need to replace
    #if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
    #    . /etc/bash_completion
    #fi
    
    with
    if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
        . /etc/bash_completion
    fi
    
    i.e. removing the hash character from the start of each of those lines.

    Thanks!
    Tagged:


Comments

  • Registered Users, Registered Users 2 Posts: 6,762 ✭✭✭WizZard


    Managed to find an answer myself :) (via StackOverflow)

    For anyone else who wants to know:
    line=`awk '/enable bash completion/ {print NR}' /etc/bash.bashrc`
    sed -i "$((line+1)),$((line+3))s/^#//g" /etc/bash.bashrc
    


  • Registered Users, Registered Users 2 Posts: 37,485 ✭✭✭✭Khannie


    On linux I would do that like this:

    sed --in-place -r 's/^#//' <filename>

    That should do it I think (unless I'm missing something).


  • Moderators, Technology & Internet Moderators Posts: 1,337 Mod ✭✭✭✭croo


    Khannie wrote: »
    On linux I would do that like this:

    sed --in-place -r 's/^#//' <filename>

    That should do it I think (unless I'm missing something).
    Would that not remove all comments?


  • Registered Users, Registered Users 2 Posts: 3,745 ✭✭✭laugh


    You can do a multi line select with vim visual mode.


  • Registered Users, Registered Users 2 Posts: 37,485 ✭✭✭✭Khannie


    croo wrote: »
    Would that not remove all comments?

    See I knew I was missing something. ;)

    There is a feature in sed that let's you select start and end points (I'll paste it in later) but I can't seem to manage to get a replace in with that too, it just spits it to stdout.


  • Advertisement
  • Moderators, Technology & Internet Moderators Posts: 1,337 Mod ✭✭✭✭croo


    yeah, it's the 3 lines that makes it tricky but I think WizZards own provided solution is the ticket.


Advertisement