When searching through code, I'm trying to write a regular expression that needs to search for a literal dollar sign immediately preceding a variable.
$ cat file1
a
b
c
$c1
$c2
d
$c-falaffel
$f
I want a grep expression that, when passed "c", returns:
$c1
$c2
$c-falaffel
What I have so far:
mode="c"
grep "\\$${mode}" file1
But the shell keeps interpreting $$ as asking for the pid. How in hell do you search an expression that is defined in a variable with a literal dollar sign in front??
Oh, and it has to be good in POSIX-compliant shells (it needs to run on the busybox shell), so bashisms are not acceptable.
you've got one too many backslashes
$ mode="c"
$ grep "\$$mode" file1
$c1
$c2
$c-falaffel
$
tested in bash 4.2.20, ksh 93u+, and zsh 5.0.5
This might be close to what you need:
awk -v RS= -v var="$mode" 'sub(".*if [$]" var "_mode","")' "$0"
or maybe this:
awk -v RS= -v var="$mode" 'match($0,"if [$]" var "_mode"){print substr($0,RSTART)}' "$0"
Once you post some input and output we'll have a better idea.
Very similar to Ed Morton's answer: you have to build the string.
search_string='$'
search_string="${search_string}$mode"
grep "$search_string" file1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.