Lucio Paoletti
Lucio Paoletti

Reputation: 371

print value into sed -n

I use sed to get the content of file from a desire point but I have a problem.

I can not print $variable value into this sed command

count=$(sed -n '/$variable/,$p' file.log | grep '"KO"' -c)

I try with double quotes and close the single but not working

count=$(sed -n "/$variable/,$p" file.log | grep '"KO"' -c) ERROR unexpected `,' count=$(sed -n '/'$variable'/,$p' file.log | grep '"KO"' -c) ERROR unterminated address regex

I know that the sed reseach is letteral "$variable" but I can not pass the value...

Thanks in advance.

Upvotes: 1

Views: 467

Answers (2)

Thor
Thor

Reputation: 47089

It's a question of getting the quoting right.

Your first example:

count=$(sed -n '/$variable/,$p' file.log | grep '"KO"' -c)

doesn't expand $variable because it's in single quotes, the second:

count=$(sed -n "/$variable/,$p" file.log | grep '"KO"' -c)

expands $variable but has issues with its contents, as mentioned by choroba. It also has issue with the $p which will be interpreted as a shell variable. Your third example:

count=$(sed -n '/'$variable'/,$p' file.log | grep '"KO"' -c)

comes pretty close to what you need, but still suffers if $variable contains characters that sed treats specially, so these need to be escaped, e.g. the following works:

variable="\[17-09-12 00:01:03\]"
count=$(sed -n '/'$variable'/,$p' file.log

And as brackets are also special to the shell you can escape them automatically with the printf %q directive:

variable="[17-09-12 00:01:03]"
variable=$(printf "%q" "$variable")
count=$(sed -n '/'$variable'/,$p' file.log

Upvotes: 2

choroba
choroba

Reputation: 241768

[ has a special meaning in sed. I would use something more powerful than sed, i.e. Perl. It can escape the variable for you:

perl -ne '/\Q'"$variable"'\E/ and print'

Upvotes: 1

Related Questions