为什么使用变量时我的sed命令失败? [英] Why is my sed command failing when using variables?

查看:40
本文介绍了为什么使用变量时我的sed命令失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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命令失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆