0

I have a UNIX script that has nawk block inside it (This is just a part of the UNIX and NAWK script. It has many more logic and the below code should definitely be in nawk) This block that reads a lookup value for Country ISO code from a file that has country and country code values and I face an issue whenever there is a bracket in the country name () or a single apostrope '

Sample values

CIV@COTE D'IVOIRE
COD@CONGO, Democratic Republic of (was Zaire)

Can you pls help me overcome these 2 issues.for a single apostrope can I have it removed from the string or is there any way I can just fine tune the existing code

Code

processbody() {

nawk '{

            COUNTRY_NAME = "COTE D'IVOIRE"


            if (COUNTRY_NAME != " "){

                       file = "/tmp/country_codes.txt"
                      FS = "@"
                      while( getline < file ) {
                      if( $0 ~ COUNTRY_NAME ) {
                      COUNTRY_CODE = $1
                       }
                       }
                       close( file )



            }

printf("%s\n",COUNTRY_CODE) > "/tmp/code.txt"

 }' /tmp/file.txt

}

4

3 回答 3

1

您需要了解 Unix shell 在哪里处理引号以及 Awk 在哪里处理引号。

鉴于您需要在脚本中同时使用单引号和双引号,我认为您最好使用awk程序文件来包含脚本,然后使用:

awk -f awk.script [file1 ...]

这避免了 shell 是否会理解它的所有问题。

如果您不能这样做,那么您可能应该继续使用单引号将 awk 脚本括起来,但每次出现

'

脚本内部必须替换为:

'\''

第一个引号终止流行的单引号字符串。反斜杠引号将单引号嵌入到字符串中。第三个引号恢复正常的单引号字符串操作,其中唯一的特殊字符是单引号。

于 2011-07-18T20:29:18.233 回答
0

如果此代码以这种形式出现在 shell 脚本中,您需要使用反斜杠转义单引号,以便它不会终止 nawk 代码。就像是:

COUNTRY_NAME = "COTE D\'IVOIRE"

在括号的情况下,您需要在字符串中对其进行转义,以便 nawk 不会将其视为正则表达式分组运算符:

COUNTRY_NAME = "CONGO, Democratic Republic of \\(was Zaire\\)"
于 2011-07-18T04:23:18.737 回答
0

显然是引用的问题。-v使用该选项将值传递给 nawk 。

代替

nawk '{
        COUNTRY_NAME = "COTE D'IVOIRE"
        if (COUNTRY_NAME != " "){ ...

利用

nawk -v "COUNTRY_NAME=COTE D'IVOIRE" '{
        if (COUNTRY_NAME != " "){ ...
于 2011-07-18T10:50:41.480 回答