我的 Bash 脚本:
declare -a lang=('english' 'spainsh')
sms="Free msg: Due to upgrades on apps you’ll need a new version by yyyy/mm/dd to app running. Visit a store or go to"
url="google.com/UA2392 to upgrade your app."
awk '{print $1 "," '${servicegrade[0]}' "," '${lang[1]}' ",,," '$sms' "," '$url'}' inputfile.csv > inputfile.txt
错误:
awk: cmd. line:1: {print $1 "," 267 "," en ",,," Free
awk: cmd. line:1: ^ unexpected newline or end of string
答案1
awk
您看到的问题与您引用(或更准确地说,不引用)命令行和内插 shell 变量的方式直接相关。 (对于 shell 和awk
.)
你有这个:
awk '{print $1 "," '${servicegrade[0]}' "," '${lang[1]}' ",,," '$sms' "," '$url'}' inputfile.csv > inputfile.txt
根据经验,我可以从错误消息中看到servicegrade=267
, lang=en
, sms=Free msg:...
, 但url
不可见(没关系),所以我们假设url=http://example.net
。
重要的部分是查看命令行上的报价。 “单引号”内的任何内容都被视为单个命令行。如果您将单引号与双引号相邻,您也可以(echo 'hello'"world"
只有一个参数)。但是,一旦引入未加引号的空格,它就会成为第二个参数(echo 'hello' "world"
是两个单词,而不是一个)。此外,您的变量都没有被引用,因此它们的值中的任何空格都将被 shell 视为断字。
让我们假设这些变量不包含空格,并将它们插入命令行中,就好像它们是实际值而不是变量一样:
awk '{print $1 "," '267' "," 'en' ",,," 'Free msg:...' "," 'http://example.net'}' inputfile.csv > inputfile.txt
现在我们将删除多余的引号:
awk '{print $1 "," 267 "," en ",,," Free msg:..."," http://example.net}' inputfile.csv > inputfile.txt
很快就会意识到awk
现在看到的是未加引号的字符串,它不能将其视为awk
变量。我怀疑你真正想要的是这样的:
awk '{print $1 ",267,en,,,Free msg:...,http://example.net"}' inputfile.csv > inputfile.txt
(如果您的输出也是 CSV 样式,则可能使用双引号参数)。
我们可以轻松地反转该过程以允许对 shell 变量进行插值,但更好的方法是将这些 shell 变量分配给awk
变量并使用它们:
awk -v servicegrade="${servicegrade[0]}" -v lang="${lang[1]}" -v sms="$sms" -v url="$url" '{print $1 "," servicegrade "," lang ",,," sms "," url}' inputfile.csv > inputfile.txt
如果您决定输出文本需要双引号参数,awk
(好吧,至少我的版本)理解这种结构:awk '{print $1 "\"" servicegrade "\",\"" lang "\",\"" sms "\",\"" url "\""}'