问题描述
我有一个带有nawk块的UNIX脚本(这只是UNIX和NAWK脚本的一部分.它具有更多的逻辑,下面的代码肯定应该在nawk中)此代码块从具有国家和地区代码值的文件中读取国家/地区ISO代码的查找值,并且当国家/地区名称中包含方括号()时,我都会遇到问题或单个撇号'
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
}
推荐答案
您需要了解Unix shell在哪里处理引号,而Awk在哪里处理引号.
You need to understand where the Unix shell is handling quotes and where Awk is handling quotes.
鉴于您需要在脚本中使用单引号和双引号,我认为最好使用awk
程序文件来包含脚本,然后使用:
Given your need for both single quotes and double quotes in the script, I think you would be best off using an awk
program file to contain the script, and then using:
awk -f awk.script [file1 ...]
这避免了shell是否会理解的所有问题.
This avoids all the issues of whether the shell is going to understand it or not.
如果您不能这样做,则可能应该继续使用单引号将awk脚本括起来,但是每次出现
If you can't do that, then you should probably continue using single quotes to surround the awk script, but each occurrence of
'
脚本内必须替换为:
'\''
第一个引号会终止当前的单引号字符串.反斜杠引号将单引号嵌入到字符串中.第三引号继续正常的单引号字符串操作,其中唯一的特殊字符是单引号.
The first quote terminates the prevailing single-quoted string. The backslash-quote embeds a single quote into the string. The third quote resumes normal single-quoted string operation, where the only special character is single quote.
这篇关于UNIX Shell脚本和AWK脚本的转义引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!