【问题标题】:How do I escape apostraphes within an awk statement?如何在 awk 语句中转义撇号?
【发布时间】:2017-06-30 14:42:38
【问题描述】:

我在 Mac Sierra 上使用 bash shell。如何在 awk 语句中转义撇号?我正在尝试以下方法

localhost:myproject davea$ awk -F\, {printf "update my_table_user set thirdparty_user_id='\''%s'\'' where thirdparty_user_id='\''%s'\'';\n", $(NF-2),$(NF-1)} /tmp/myfile.csv
-bash: NF-2: command not found
-bash: NF-1: command not found
awk: syntax error at source line 1
 context is
     >>>  <<<
awk: illegal statement at source line 1
    missing }

但正如您所见,它会导致一系列错误。我的目标是从 CSV 文件中提取第二列和第三列,并从中创建一条 SQL 语句。

【问题讨论】:

  • 你有一个 SQL 注入攻击等待发生。

标签: bash shell awk escaping apostrophe


【解决方案1】:

您可以使用\047 作为单引号:

awk -F, '{
printf "update my_table_user set thirdparty_user_id=\047%s\047 where thirdparty_user_id=\047%s\047;\n",
$(NF-2),$(NF-1)}' /tmp/myfile.csv

【讨论】:

  • 谢谢,这似乎解决了所有的语法错误,但是如何提取第二列和第三列?以上似乎是在提取第一列和第二列。
  • 我刚刚采用了您的示例 awk 命令,该命令仅适用于 2 个 csv 字段。您可以使用 $1, $2, $3 等访问这些 csv 字段中的任何一个。
  • 例如可以使用:awk -F, '{printf "update my_table_user set thirdparty_user_id=\047%s\047 where thirdparty_user_id=\047%s\047;\n", $2, $3}' file.csv
猜你喜欢
  • 1970-01-01
  • 2012-03-24
  • 1970-01-01
  • 1970-01-01
  • 2018-06-12
  • 2011-01-27
  • 2010-10-23
相关资源
最近更新 更多