1

我有一个文件,我想用类似"Nov 30"or的字符串 grep 出行"Nov 30" (基本上我不想指定中间的空格数。

在终端这会很好,我会这样做:

grep 'Nov * 30' file

但是,为了我的目的,最好保持通用,所以实际上我想做一些类似的事情:

grep "$(date +%b) * $(date +%d)" file

这很好,但我实际上想通过 ssh 来做到这一点,所以它就像

ssh -t host "grep "$(date +%b) * $(date +%d)" file"

在这一点上,我遇到了问题。它不是仅针对 11 月 30 日类型的日期字符串进行 grepping,而是返回各种不同的 11 月日期。我觉得这个问题与双引号的使用有关(也许 -t 参数的第一组双引号影响了第二批,但我不知道如何解决这个问题),我从中看到回答“bash 将在本地计算机上的双引号内评估和替换变量,但会在单引号内的目标计算机上执行此操作”。所以我尝试用

ssh -t host "grep '$(date +%b) * $(date +%d)' file"

但是现在 grep 根本不返回任何结果!我认为这是因为我正在寻找文字'$(date +%b)......'而不是替代的'Nov..',但是我不明白为什么第一次尝试使用双引号没有工作。

欢迎任何帮助

4

3 回答 3

1

逃避你的报价:

ssh -t host "grep \"$(date +%b) * $(date +%d)\" file"
于 2013-11-30T20:39:38.253 回答
0

In this version the date command will be executed locally:

ssh -t host "grep '$(date +%b) * $(date +%d)' file"

In this version the date command will be executed on the remote host:

ssh -t host 'grep "$(date +%b) * $(date +%d)" file'

This can make a difference when your local PC and server are in different time zone. Right now for example, it's Dec 1 in France, but Nov 30 on my server in the US.

In the 1st version the $() within the double quotes are evaluated before sending to the server. So the command sent to the server is grep 'Dec * 1' file in my timezone.

In the 2nd version the $() within single quotes are NOT evaluated before sending to the server. So the command sent to the server is grep "$(date +%b) * $(date +%d)" file, and so the server will evaluate the $() within double quotes.

于 2013-11-30T23:09:29.707 回答
0

或者,单引号您希望在远程计算机上执行的命令行。(在这种情况下,date命令将在远程端执行。)

ssh -t host 'grep "$(date +%b) * $(date +%d)" file'
于 2013-11-30T20:44:00.600 回答