Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my sed command failing when using variables?

using bash, I'm trying to insert a variable for the date and search a log file for that date, then send the output to a file. If I hardcode the date like this it works:

sed -n '/Nov 22, 2010/,$p' $file >$log_file

but if I do it like this it fails:

date="Nov 22, 2010"
sed -n '/$date/,$p' $file >$log_file

The error I get is: sed: 1: "/Nov 22, 2010/,": expected context address Thanks for the help.

like image 346
Ronedog Avatar asked Feb 25 '23 18:02

Ronedog


1 Answers

In shell scripts, there is a difference between single and double quotes. Variables inside single quotes are not expanded (unlike those in double quotes), so you would need:

date="Nov 22, 2010"
sed -n "/$date/,\$p" $file >$log_file

The backslash escapes the dollar sign that should be taken literally by the shell and has a meaning to sed.

like image 121
PleaseStand Avatar answered Feb 28 '23 06:02

PleaseStand