为什么我无法在gawk中转义报价? [英] Why can't I escape quote in gawk?
问题描述
我正在尝试执行以下操作,但是要么我太累了,无法思考,要么逃生过程中出现了奇怪的事情:
I'm trying to do the following, but either I'm way too tired and can't think, or something weird is hapening with the escapes:
scanimage -L | gawk '/N650U/ {print gensub("[\'`]", "", "g", $2)}'
pipe bquote>
推荐答案
惯用的做法是创建一个包含单引号的变量,然后使用该变量:
The idiom to do this is to create a variable which contains the single quote and then use that:
scanimage -L | gawk '/N650U/ {print gensub(q"`", "", "g", $2)}' q="'"
但是,由于您是在字符类中使用它的,因此无法正常工作,因此您需要执行以下操作:
However, since you are using it in a character class, that is not going to work so you'll need to do this:
scanimage -L | gawk '/N650U/ {print gensub("[`'\'']", "", "g", $2)}'
<-- 1st pair --> <-- 2nd pair -->
如果使用bash
的另一种选择是使用 支持转义单引号的$''
Another alternative if using bash
is to use $''
which does support escaping single-quotes
scanimage -L | gawk $'/N650U/ {print gensub("[`\']", "", "g", $2)}'
在第二种情况下,您要做的就是在字面单引号之前创建一个单引号对,转义该单引号,以便外壳程序不解释它,然后在其后再创建另一个单引号对./p>
在正则表达式中使用单引号的示例
All you are doing in the 2nd case is creating a single-quote pair right before your literal single-quote, escaping the single quote so the shell doesn't interpret it and then make another single-quote pair after it.
$ echo $'foo`\'' | awk '{gsub(/[o`'\'']/,"#")}1'
f####
在正则表达式外使用单引号的示例
$ echo "foo" | awk '{print q$0q}' q="'"
'foo'
在$''
中包含单引号的示例
Example with single-quote inside $''
echo $'foo`\'' | awk $'{gsub(/[o`\']/,"#")}1'
f####
这篇关于为什么我无法在gawk中转义报价?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!