Otis Wright Otis Wright - 7 months ago 12
Bash Question

Using sed with regex to find and replace a string

So I have the following string in my

config.fish
, and
init.vim
:

Fish:
eval sh ~/.config/fish/colors/base16-monokai.dark.sh


Vim:
colorscheme base16-monokai


Vim:
let g:airline_theme='base16_monokai'


And I have the following shell script:

#!/bin/sh

theme=$1
background=$2

if [ -z '$theme' ]; then

echo "Please provide a theme name."

else

if [ -z '$background' ]; then
$background = 'dark'
fi

base16-builder -s $theme -t vim -b $background > ~/.config/nvim/colors/base16-$theme.vim &&
base16-builder -s $theme -t shell -b $background > ~/.config/fish/colors/base16-$theme.$background.sh &&
base16-builder -s $theme -t vim-airline -b $background > ~/.vim/plugged/vim-airline-themes/autoload/airline/themes/base16_$theme.vim

sed -i -e 's/foo/eval sh ~/.config/fish/colors/base16-$theme.$background.sh/g' ~/Developer/dotfiles/config.fish
sed -i -e 's/foo/colorscheme base16-$theme/g' ~/Developer/dotfiles/init.vim
sed -i -e 's/foo/let g:airline_theme='base16_$theme'/g' ~/Developer/dotfiles/init.vim


fi


Basically the idea is the script will generate whichever theme is passed through using this builder.

I have tried referring this documentation but I am not very skilled at regex so if anybody could give me a hand I would appreciate it.

What I need to happen is once the script is generated
sed
will look for the above strings and replace theme with the newly generated theme ones.

Answer

Try this :

sed -i "s|\(eval sh ~/\.config/fish/colors/base16-\)\([^.]*\)\.\([^.]*\)\\(.*\)|\1$theme.$background\4|
" ~/Developer/dotfiles/config.fish
sed -i "s/\(base16\)\([-_]\)\([a-zA-Z]*\)/\1\2$theme/g" ~/Developer/dotfiles/init.vim

Assuming in the second sed command that the theme is an alphanumeric string. If not, you can complete the character range : [a-zA-Z] with additional characters (eg [a-zA-Z0-9]).