Daniela Morais
Daniela Morais

Reputation: 2237

Search and replace a specific line with bash

I need add new plugins in my zshrc file using bash script, to do that I search the line which contains plugins = (sometext)

syntax

plugin_text=$(grep "^[^#;]" zshrc | grep -n "plugins=(.*)")

running directly in terminal I get:

$ grep "^[^;]" zshrc | grep -n "plugins=(.*)"
38:# Example format: plugins=(rails git textmate ruby lighthouse)
40:plugins=(git python pip)

40 is the correct line but when I execute my bash script I get:

$ ./config-minimal
3:plugins=(git python pip)

I need change 40 line inserting new plugins. Example:

before

plugins=(git python pip)

after

plugins=(git python pip zsh-autosuggestions zsh-syntax-highlighting)

How can I get this line and replace text with a easy way?

My script

function install_zsh {
    # aptitude install zsh
    # sh -c "$(wget https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)"
    # Install zsh highlighting 
    # cd ~/.oh-my-zsh/custom
    # git clone https://github.com/zsh-users/zsh-syntax-highlighting.git
    # Install zsh auto suggestions
    # git clone git://github.com/zsh-users/zsh-autosuggestions 
    # TODO: Add options in plugins 
    cd ~
    plugin_text=$(grep "^[^#;]" .zshrc | grep -n "plugins=(.*)")
    new_plugins=${plugin_text/)/ zsh-autosuggestions zsh-syntax-highlighting)}
    line_number=${plugin_text/:plugins*/ }
    sed "$(line_number)s/plugin_text/new_plugins/" .zshrc
}

Upvotes: 2

Views: 963

Answers (1)

Juan Diego Godoy Robles
Juan Diego Godoy Robles

Reputation: 14955

You can handle it with a simple sed:

sed 's/^plugins=(\(.*\)/plugins=(zsh-autosuggestions zsh-syntax-highlighting \1/' .zshrc

Or (thx @123):

sed 's/\(^plugins=([^)]*\)/\1 zsh-autosuggestions zsh-syntax-highlighting/' .zshrc

Add -i flag to infile replacement.


function install_zsh {
    # aptitude install zsh
    # sh -c "$(wget https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)"
    # Install zsh highlighting 
    # cd ~/.oh-my-zsh/custom
    # git clone https://github.com/zsh-users/zsh-syntax-highlighting.git
    # Install zsh auto suggestions
    # git clone git://github.com/zsh-users/zsh-autosuggestions 
    # TODO: Add options in plugins 

    sed -i.bak 's/^plugins=(\(.*\)/plugins=(zsh-autosuggestions zsh-syntax-highlighting \1/' ~/.zshrc
}

Upvotes: 2

Related Questions