python - 处理 unix 中文件名中的无效字符

标签 python linux bash unix special-characters

我需要对带有“!”的文件进行一些linux命令操作就像文件名中的字符一样。但每当我尝试执行命令时,都会出现以下错误。

[root@ATD-6000 ~]# cat a!aapoorv.txt
-bash: !aapoorv.txt: event not found

我正在使用 paramiko 模块在 python 中执行这些命令。我无法使用原始字符串 r'filestringname',因为我正在从数据库本身读取字符串名称。

如何使用 python/bash 转义/处理这些字符之王。

最佳答案

试试这个:

cat a\!aapoorv.txt

或者这个

cat 'a!aapoorv.txt'

Note that while cat a\!aapoorv.txt works in all shells that implement that csh-style history expansion, cat 'a!aapoorv.txt' doesn't work in csh/tcsh.

有关更多信息,您可以参阅 man bash 关于QUOTING

以下是该文档的一些内容:

Quoting is used to remove the special meaning of certain characters or words to the shell.

Quoting can be used to disable spe‐cial treatment for special characters, to prevent reserved words from being recognized as such, and to prevent parameter expan‐sion.

这是输出:

[kevin@Arch test]$ ls
a!aapoorv.txt
[kevin@Arch test]$ cat a\!aapoorv.txt 
Hello, This is a test
[kevin@Arch test]$ cat 'a!aapoorv.txt'
Hello, This is a test

在Python上,你不需要转义特殊字符,这是一个测试:

>>> with open('a!aapoorv.txt') as f:
...     f.read()
...     
... 
'Hello, This is a test\n'
>>> with open(r'a!aapoorv.txt') as f:
...     f.read()
...     
... 
'Hello, This is a test\n'
>>> 

关于python - 处理 unix 中文件名中的无效字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32678768/

相关文章:

python - "Initializing"包含 python 文件的常量?

python将不同的**kwargs传递给多个函数

linux - 传播由子执行脚本完成的变量更改

linux - Bash 脚本打印出二进制文件的内容,一次一个字,不带 xxd

linux - 如何在 BASH 中捕获 href 链接

bash - 使用 xargs 显示 git 别名中的命令

python - 使用 Opencv python 查找灰度或彩色图像

Python:计算列表列表中的元素数量并提供给矩阵?

node.js - 如何设置服务器运行 Node.js?

linux - Grep 从一个文件中获取一个文件列表并根据条件打印该行的特定部分