I have a text file, named my_data.txt, with the following contents:
# define var1 and var2
var1=101
var2=202
// display var1 and var2
echo ${var1}
echo ${var2}
I want search all occurrences of var1 but not those in a line starts with '#' or '//'. I can do this:
grep var1 my_data.txt | grep -v '^#' | grep -v '^//'
output:
var1=101
echo ${var1}
The results is correct. The question: is there any way to pass both values '^#' and '^//' to a single -v option?
CodePudding user response:
I suggest:
grep -v -e '^#' -e '^//' file | grep 'var1'
Or with an extended regular expression (-E
):
grep -v -E '^(#|//)' file | grep 'var1'
Output:
var1=101 echo ${var1}
CodePudding user response:
If you can make use of grep -P you can use a Perl-compatible regular expression and a single grep command.
grep -P "^(?!#|//).*\bvar1\b" my_data.txt
The pattern matches
^
Start of string(?!#|//)
Negative lookahead, assert not#
or//
.*\bvar1\b
Match the word var1 in the line
Or using awk
skipping the line that starts with # or // and print a line that contains var1
awk '/^(#|\/\/)/{next};index($0, "var1")' my_data.txt
The examples will output:
var1=101
echo ${var1}