I want to grep a string from a given character or pattern until another given character or pattern instead of the entire line.
For example:
$ > echo "The brown fox jumps over the lazy dog" | grep -option "b" "s"
brown fox jumps
$ > echo "The brown fox jumps over the lazy dog" | grep -option "the l" "g"
the lazy dog
What I actually need it for is to grep a path when I use dirs -v
so that I can do this:
$ > ls -AF
file.txt github/ .vim/
$ > dirs -v
0 ~
1 ~/.vim/pack/themes
2 ~/.vim/colors
3 ~/github/dirname
4 ~/github/repo/
$ > mv -v file.txt $(dirs -v | grep 2 | grep -option "~" "colors")
renamed 'file.txt' -> '~/.vim/colors/file.txt'
I used grep twice so that I can only match the ~
with the one from the line containing 2
. Is there a way to accomplish this as a shell function/alias in my .zshrc?
ANSWER: I simply used mv file.txt ~2
from one of the answers below. I didn't even think I could do that, lol.
I also put these lines in my .zshrc from one of the answers below.
function grepo () { grep -Po "${1}.*?${2}" }
alias -g GO='| grepo'
so that I can use it like so:
$ > echo "the brown fox jumps over the lazy dog" GO b s
brown fox jumps
$ > echo "the brown fox jumps over the lazy dog" GO "the l" g
the lazy dog
$ > echo "the brown fox jumps over the lazy dog" GO fox over
fox jumps over
For my problem, it didn't work though for some reason I can't think of.
$ > ls -AF
file.txt github/ .vim/
$ > dirs -v
0 ~
1 ~/.vim/pack/themes
2 ~/.vim/colors
3 ~/github/dirname
4 ~/github/repo/
$ > mv file.txt $(dirs -v GO "~/.v" "themes")
mv: cannot move 'file.txt' to '~/.vim/pack/themes': No such file or directory
grepo () grep -Poe "$1.*?$2"
(to avoid problems when$1
starts with-
, or evangrepo () grep -Po "\Q$1\E.*?\Q$2\E"
, so$1
and$2
are not interpreted as regexps (like your~/.v
case where.
otherwise matches any single character). – Stéphane Chazelas May 15 '20 at 12:46