[英]AWK with If condition
i am trying to replace the following string for ex: from 我正在尝试将以下字符串替换为ex:from
['55',2,1,10,30,23],
to 至
['55',2,555,10,30,23],
OR 要么
['55',2,1,10,30,23],
to 至
['55',2,1,10,9999,23],
i search around and find this : 我到处寻找,发现:
$ echo "[55,2,1,10,30,23]," | awk -F',' 'BEGIN{OFS=","}{if($1=="[55"){$2=10}{print}}'
[55,10,1,10,30,23],
but it's not working in my case since there is " ' " around the value of $1 in my if condition : 但在我的情况下不起作用,因为在if条件中,$ 1的值周围有“”:
$ echo "['55',2,1,10,30,23]," | awk -F',' 'BEGIN{OFS=","}{if($1=="['55'"){$2=10}{print}}'
['55',2,1,10,30,23],
The problem is not in the awk code, it's the shell expansion. 问题不在于awk代码,而是shell扩展。 You cannot have single quotes in a singly-quoted shell string.
在单引号的shell字符串中不能有单引号。 This is the same problem you run into when you try to put the input string into single quotes:
当您尝试将输入字符串放在单引号中时,会遇到相同的问题:
$ echo '['55',2,1,10,30,23],'
[55,2,1,10,30,23],
-- the single quotes are gone! -单引号不见了! And this makes sense, because they did their job of quoting the
[
and the ,2,1,10,30,23],
(the 55
is unquoted here), but it is not what we wanted. 这是有道理的,因为他们做了引述
[
和,2,1,10,30,23],
(此处未引用55
),但这不是我们想要的。
A solution is to quote the sections between them individually and squeeze them in manually: 一种解决方案是分别引用它们之间的节,然后手动将其压缩:
$ echo '['\''55'\'',2,1,10,30,23],'
['55',2,1,10,30,23],
Or, in this particular case, where nothing nefarious is between where the single quotes should be, 或者,在这种情况下,单引号之间应该没有任何恶意的地方,
echo '['\'55\'',2,1,10,30,23],' # the 55 is now unquoted.
Applied to your awk code, that looks like this: 应用于您的awk代码,如下所示:
$ echo "['55',2,1,10,30,23]," | awk -F',' 'BEGIN{OFS=","}{if($1=="['\'55\''"){$2=10}{print}}'
['55',10,1,10,30,23],
Alternatively, since this doesn't look very nice if you have many single quotes in your code, you can write the awk code into a file, say foo.awk
, and use 或者,由于如果代码中有很多单引号,这看起来不太好,所以可以将awk代码写入文件中,例如
foo.awk
并使用
echo "['55',2,1,10,30,23]," | awk -F, -f foo.awk
Then you don't have to worry about shell quoting mishaps in the awk code because the awk code is not subject to shell expansion anymore. 然后,您不必担心awk代码中的shell引用错误,因为awk代码不再受shell扩展的约束。
I think how to match and replace is not the problem for you. 我认为如何匹配和替换对您来说不是问题。 The problem you were facing is, how to match a single quote
'
in field. 您面临的问题是,如何在字段中匹配单引号
'
。
To avoid to escape each '
in your codes, and to make your codes more readable, you can assigen the quote to a variable, and use the variable in your codes, for example like this: 为了避免转义代码中的每个
'
,并使代码更具可读性,您可以将引号关联到变量,然后在代码中使用该变量,例如:
echo "['55' 1
['56' 1"|awk -v q="'" '$1=="["q"55"q{$2++}7'
['55' 2
['56' 1
In the above example, only in line with ['55'
, the 2nd field got incremented. 在上面的示例中,仅与
['55'
,第二个字段才增加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.