如何转义整个变量?

如何转义整个变量?

在这个问题的回答中:

https://superuser.com/questions/163515/bash-how-to-pass-command-line-arguments-containing-special-characters

它说我们必须将函数的参数放在双引号中以转义整个参数(如"[abc]_[x|y]")。

但是如果特殊字符位于"( ) 开头"[abc]_[x|y]",我们就不能执行以下操作:

program  ""[abc]_[x|y]"  anotheragument

"在这种情况下我怎样才能逃脱呢?

答案1

如果我理解正确,您的变量中有一个正则表达式模式,并且您希望grep使用它而不给正则表达式元字符赋予任何特殊含义。如果是这种情况,则-F(fixed strings) 选项grep就是您想要的:

grep -F "$var" your_file

您的系统可能还有一个fgrep与上述等效的特殊命令 ( ):

fgrep "$var" your_file

答案2

单引号应该可以实现你想要的。

# " is the special charater
var='"hello "word";'
grep "$var" file

从 bash 手册页:

Enclosing characters in single quotes preserves the literal value of each character within the quotes.  A  single  quote  may  not
   occur between single quotes, even when preceded by a backslash.

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.

相关内容