Home > Software engineering >  Sed substitute one extra line
Sed substitute one extra line

Time:02-21

I wrote regexp to find and replace line. But for some reason sed command replaces one empty line after founded expected line.

You can look on it on regexp online website: https://regex101.com/r/5NAAz9/1

Command:

plugins_string="plugins=(docker docker-compose yarn tmux git vi-mode autojump web-search zsh-navigation-tools zsh-interactive-cd colored-man-pages zsh-autosuggestions)"

sed -E "s/^plugins=\(\n?(\n. )*.*(\n. )*/${plugins_string}/pg" ./.zshrc

Input:

# Add wisely, as too many plugins slow down shell startup.
# plugins=(rails git textmate ruby lighthouse)
plugins=( docker docker-compose yarn tmux git vi-mode colored-man-pages) # <-- line to search

source $ZSH/oh-my-zsh.sh

# User configuration

Output. Replaces two lines instead of one:

```bash
# plugins=(rails git textmate ruby lighthouse)
plugins=(docker docker-compose yarn tmux git vi-mode autojump web-search zsh-navigation-tools zsh-interactive-cd colored-man-pages zsh-autosuggestions) # <-- replaced line
plugins=(docker docker-compose yarn tmux git vi-mode autojump web-search zsh-navigation-tools zsh-interactive-cd colored-man-pages zsh-autosuggestions) # <-- extra line??

source $ZSH/oh-my-zsh.sh

# User configuration

CodePudding user response:

You used p flag in you s-ubstitute command. From the manual:

If the substitution was made, then print the new pattern space.

But sed prints all lines by default anyway, so the end result is that the substituted line is printed twice. AFAIK the p flag is usually used with sed's -n option. The option disables automatic printing of all lines and with p flag you make it print only the matched lines.

In your case, just remove the p flag: s/.../.../g.

Also a remark, sed's substitute command works on line-by-line basis, so those new-lines in your pattern won't work as you might expect.

  • Related