How to escape single quote using awk in a bash script

后端 未结 4 805
不思量自难忘°
不思量自难忘° 2021-01-24 02:16

This is what I have so far, tried multiple ways but can\'t get it just right. My goal is to sanitize the input to prevent problems while inputting to mysql from text file

<
相关标签:
4条回答
  • 2021-01-24 02:54

    What you want is:

    awk '{gsub(/\047/,".")}1' file
    

    See http://awk.freeshell.org/PrintASingleQuote.

    0 讨论(0)
  • 2021-01-24 02:58

    You have used wrong quoting:

    awk '{gsub(/'"'"'/, "."); print}'
    
    0 讨论(0)
  • 2021-01-24 02:59

    Since you requested "how to escape single quote using awk" here's a solution using awk:

    awk '{ gsub("\x27", ".");print $0}'
    

    where \x27 is the escape sequence representation of the hexadecimal value 27 (a single quote).

    For a list of all escape sequences see https://www.gnu.org/software/gawk/manual/html_node/Escape-Sequences.html

    0 讨论(0)
  • 2021-01-24 03:13

    I'm not sure if I got the problem correctly. If you want to replace all occurrences of a single quote by a dot, use tr:

    tr "'" "." < file.txt > sanitized.txt
    

    If you want to escape the single quote with a backslash use sed like this:

    sed "s/'/\\\'/g" file.txt > sanitized.txt
    

    Note: Please take the advice from CharlesDuffy seriously. This is far from a stable and safe solution to escape values for an SQL import.

    0 讨论(0)
提交回复
热议问题