问题描述
我使用bash尝试为日期插入变量,并在日志文件中搜索该日期,然后将输出发送到文件.如果我这样对日期进行硬编码,它将起作用:
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
我得到的错误是: sed:1:"//Nov 22,2010/,":预期的上下文地址
感谢您的帮助.
The error I get is: sed: 1: "/Nov 22, 2010/,": expected context address
Thanks for the help.
推荐答案
在shell脚本中,单引号和双引号之间是有区别的.单引号内的变量不扩展( (不同于双引号内的变量),因此您需要:
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
反斜杠转义了美元符号,该符号应由外壳按字面意义使用,并且具有sed的含义.
The backslash escapes the dollar sign that should be taken literally by the shell and has a meaning to sed.
这篇关于为什么使用变量时我的sed命令失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!