1

I want to add zsh-autosuggestions plugin to ~/.zshrc by script.

original text:

plugins=(git)

or

 plugins=(git
 some1
 some2)

target :

plugins=(git
zsh-autosuggestions)
  1. This doesn't work.

    sed -i  's/^plugins=\(([^\)]*)\)/plugins=\(\1\nzsh-autosuggestions\n\)/' ~/.zshrc
    

    I am confused, I think this ([^\)]*) is group 1, but why it not work

  2. but remove first group's ()

    sed -i  's/^plugins=\([^\)]*\)/plugins=\(\1\nzsh-autosuggestions\n\)/' ~/.zshrc
    

    turn out to

    plugins=((git
    zsh-autosuggestions
    )
    )
    

    I have escaped the () by \, why it became group 1?

2 Answers 2

1

Sed solution:

Sample ~/.zshrc contents:

param=val1
plugins=(git)
param2=val2

plugins=(git
some1
some2)
param3=val3

sed '/^plugins=/ N;N; s/\(=([^)]*\))/\1\nzsh-autosuggestions)/' ~/.zshrc
  • N - add a newline to the pattern space, then append the next line of input to the pattern space
  • \(...\) - regex captured group; should be escaped with \ in BRE to enable its special meaning

The output:

param=val1
plugins=(git
zsh-autosuggestions)
param2=val2

plugins=(git
some1
some2
zsh-autosuggestions)
param3=val3
4
  • could you explain what N;N; and = means? In python or javascript, once () aprear(witout escape) would be considered as a group. Seems it is not so in sed.
    – Mithril
    Commented Jan 6, 2018 at 9:23
  • @Mithril, see my explanation Commented Jan 6, 2018 at 9:26
  • emmm, it is still confusing ... because I usually write regex in python, the sed match group is wrong in my viewing, regex101.com/r/DRChkE/1 . I think I need ask a question how to make sed regex work as the common standard(python or javascript , java).
    – Mithril
    Commented Jan 6, 2018 at 9:45
  • @Mithril, gnu.org/software/sed/manual/… Commented Jan 6, 2018 at 9:51
0

Below command works fine for me


Command

 echo "plugins=(git)" | sed "s/(.*[^)]/&\nzsh-autosuggestions/g"

Output

plugins=(git
zsh-autosuggestions)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .