如何检查字符串是否以包含#、制表符和空格的值开头?

amp*_*ent 3 scripting bash

在我的bash脚本中,我想检查字符串是否以# modified:或开头# new file:。在这两种情况下,# 后面的字符都是制表符。在后一种情况下,“new”和“file”之间的字符是一个空格。

我试过:

if [[ $outline == "#\tmodified:*" ]]; then

if [[ $outline == "# modified:*" ]]; then (在# 后点击实际选项卡)

但都没有奏效。我该怎么做呢?

Sté*_*las 5

使用任何 POSIX shell:

tab=$(printf '\t') # or tab='   ' # (a real tab character)
case $outline in
  ("#${tab}modified:"*) ...
esac
Run Code Online (Sandbox Code Playgroud)

ksh93,zshbash:

case $outline in
  ($'#\tmodified:'*) ...
esac
Run Code Online (Sandbox Code Playgroud)

或者:

if [[ $outline = $'#\tmodified:'* ]]; then...
Run Code Online (Sandbox Code Playgroud)

关键是:

  • * 不得引用,否则按字面理解。
  • \t仅在$'...'引用类型中扩展(或printf在格式参数中扩展)