我有包含日期和事件的日志文件。我想不时检查这个文件,只查看特定时间点的记录,例如,上次检查期间的最后一个错误。
05/03/2016 23:55:25.142639 user1
05/04/2016 12:55:25.142639 user4
05/04/2016 13:57:25.142639 user3
05/04/2016 13:51:02.236522 user2
我想把日期放在一个变量中
variable="05/04/2016 12:55:25.142639"
我尝试运行以下命令,但没有成功:
[sdtest tmp]$ sed -n "/$variable/,\$p" logfile.out
sed: -e expression #1, char 5: unknown command: `0'
最佳答案
这是因为你的命令扩展为
sed -n /05/04/2016 12:55:25.142639/,$p logfile.out
你看到问题了吗?太多的正斜杠会混淆 sed,它会尝试在地址 /05/
处执行命令 0
。
要解决这个问题,您必须使用不同的地址定界符。与 s///
不同,您可以在 s|||
中使用不同的分隔符,对于地址,您必须转义第一个分隔符,例如:
$ sed -n "\|$variable|,\$p" logfile.out
05/04/2016 12:55:25.142639 user4
05/04/2016 13:57:25.142639 user3
05/04/2016 13:51:02.236522 user2
引自manual :
\%regexp%
(The
%
may be replaced by any other single character.)This also matches the regular expression regexp, but allows one to use a different delimiter than
/
. This is particularly useful if the regexp itself contains a lot of slashes, since it avoids the tedious escaping of every/
. If regexp itself includes any delimiter characters, each must be escaped by a backslash (\
).
注意:为了避免使用双引号引起的转义问题,我们也可以只在 shell 变量周围使用双引号,其余部分使用单引号:
sed -n '\|'"$variable"'|,$p' logfile.out
关于linux - 使用 sed 和变量剪切日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37311453/