【问题标题】:Escaping exclamation mark in touch string [duplicate]在触摸字符串中转义感叹号[重复]
【发布时间】:2018-11-25 17:17:24
【问题描述】:

每次我下载 youtube 文件(例如 abc.mp4)时,我都会立即通过在 bash 终端中手动执行以下命令来更改其日期/时间戳:touch -d "$(date)" "abc.mp4"

当文件具有嵌入的感叹号(例如ab!c.mp4)时,这可以正常工作除了。然后,以下命令出现故障:touch -d "$(date)" "ab!c.mp4"

实验,我试过了:touch -d "$(date)" "ab\!c.mp4"不高兴,触摸命令创建了一个名为ab\!c.mp4的新空文件。

我的 kludgy 解决方案是手动重命名 youtube 文件,删除其名称中的感叹号,然后执行 touch 命令。

有没有更优雅的方法让感叹号保留在文件名中?

【问题讨论】:

  • 你试过用单引号吗? 'ab!c.mp4'
  • @TrebuchetMS 不,我没有。单引号很好用在这里。谢谢,这不会发生在我身上。

标签: string bash escaping


【解决方案1】:

尝试在您的touch 命令之前调用set +H,或者只使用单引号:touch -d "$(date)" 'ab!c.mp4'

【讨论】:

  • 谢谢,工作就像一个魅力。
【解决方案2】:

关闭历史扩展(设置+H)或使用单引号。例如:

$ echo "foo!bar"
bash: !bar": event not found
$ echo 'foo!bar'
foo!bar
$ set +H
$ echo "foo!bar"
foo!bar

来自手册页:

Only backslash (\) and single quotes can quote the history expansion character.

另外,供参考:

Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !.  The characters $ and ` retain their special meaning within double quotes.  The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \,  or <newline>.   A  double  quote  may  be quoted within double quotes by preceding it with a backslash.  If enabled, history expansion will be performed unless an !  appearing in double quotes is escaped using a backslash.  The backslash  preceding the !  is not removed.

【讨论】:

  • 谢谢,有趣的想法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
  • 1970-01-01
相关资源
最近更新 更多