开发者

UNIX AWK escaping single quotes [duplicate]

开发者 https://www.devze.com 2023-03-21 07:22 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: UNIX shell script and escaping quotes for AWK script
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

UNIX shell script and escaping quotes for AWK script

I开发者_C百科 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 '

These are just sample values and it can have many countries with single quote and parantheses

Sample values

CIV@COTE D'IVOIRE
COD@CONGO, Democratic Republic of (was Zaire)
HRV@CROATIA (local name: Hrvatska) 

Can you pls help me overcome these 2 issues of if a string has a single quote or parantheses.

Is there anyway I can escape this single quote and apostrope dynamically ?

Code

processbody() {

nawk '{

           // These are sample values not exhaustive
           COUNTRY_NAME = "COTE D'IVOIRE" // this is read dynamically inside nawk
           #COUNTRY_NAME = "CONGO, Democratic Republic of (was Zaire)"  // this is read dynamically inside nawk
           #COUNTRY_NAME = "CROATIA (local name: Hrvatska)"  // this is read dynamically inside nawk
            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
  }

  processbody


You have a couple of problems. Hardcoding a single quote inside a single quoted string (the nawk body), and the fact that you're using the ~ operator which does regular expression matching, not string comparison.

What do you mean by "this is read dynamically inside nawk"? In your example you're hardcoding the value. Are you reading it from a file?

There are a couple of ways to get a single quote inside a single quoted string:

  1. escape the single quote with a backslash: nawk '... x="what\'s up" ...'
  2. shell string contatenation: nawk '...x="what'"'"'s up" ...'
  3. use a heredoc:

.

nawk_script=<<'END'
{ 
  x="what's up" 
  ...
}
END
nawk "$nawk_script" /tmp/file.txt

Regarding the parentheses problem, simply use a string comparison function instead of a regex matching operator:

if (index($0, COUNTRY_NAME) > 0) {
  ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消