如何通过bash shell在SQLite中转义字符? [英] How can I escape characters in SQLite via bash shell?

查看:100
本文介绍了如何通过bash shell在SQLite中转义字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用bash从命令行向SQLite发送查询。我需要对单引号和双引号都进行转义,并对其进行转义,以便bash不会误解它们。这是一个典型的查询:

I am trying to send a query to SQLite from the command line using bash. I need to escape both single quotes and double quotes, and escape them so that bash does not misinterpret them. Here is a typical query:

select * from contacts where source = "Nancy's notes";

如何从命令行发送此查询?基本语法是这样的:

How can I send this query from the command line? The basic syntax is something like this:

sqlite3.bin contacts.db 'select * from contacts where source = "Nancy's notes"'

但是在这种情况下,shell会误解单引号或双引号。我尝试使用双斜线和三斜线转义,但这是行不通的。我很迷惑。

But in this case, the shell misinterprets either the single or double quotes. I've tried escaping using both double and triple slashes but this doesn't work. I'm befuddled. Any suggestions?

推荐答案

MarkusQ解决方案的麻烦在于知道哪些字符在双引号中是特殊的-它们很多,包括反引号,美元开括号,美元变量等。

The trouble with MarkusQ's solution is knowing which characters are special inside double quotes - there are quite a lot of them, including back-ticks, dollar-open parenthesis, dollar-variable, etc.

我建议最好将字符串括在单引号内;然后,字符串中的每个单引号都需要替换为序列引号,反斜杠,引号,引号:

I would suggest it is better to enclose the string inside single quotes; then, each single quote inside the string needs to be replaced by the sequence quote, backslash, quote, quote:

sqlite3.bin contacts.db 'select * from contacts
      where source = "Nancy'\''s notes"'

替换中的第一个引号终止当前的单引号字符串;反斜杠引号表示文字单引号,最后的引号以新的单引号字符串开头。此外,这通常适用于Bourne,Korn,Bash和POSIX shell。 (C Shell和衍生产品具有更复杂的规则,需要反斜杠才能换行,以此类推。)

The first quote in the replacement terminates the current single-quoted string; the backslash-quote represents a literal single quote, and the final quote starts a new single-quoted string. Further, this works with Bourne, Korn, Bash and POSIX shells in general. (C Shell and derivatives have more complex rules needing backslashes to escape newlines, and so on.)

这篇关于如何通过bash shell在SQLite中转义字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆