如何在linux cat命令中同时处理单引号/撇号和空格?

问题描述 投票:0回答:3

我在

test's file.txt
目录中有一个名为
test's dir
的文件。 所以文件路径变成了
test's dir/test's file.txt
。 我想捕获文件的内容,但由于该文件包含撇号和空格,因此我很难实现这一点。 我尝试了几个命令,包括

  1. sh -c "cat 'test's dir/test's file.txt'"
  2. sh -c 'cat "test's dir/test's file.txt"'
  3. sh -c "cat '"'"'test's dir/test's file.txt'"'"'"
  4. sh -c 'cat "test\'s\ dir/test\'s\ file.txt"'
    还有很多 ... 但它们都不起作用。
linux bash shell operating-system cat
3个回答
2
投票

请您尝试一下:

sh -c "cat 'test'\''s dir/test'\''s file.txt'"

至于路径名部分,它是串联的:

'test'
\'
's dir/test'
\'
's file.txt'

如果你想执行

python
中的shell命令,请尝试:

#!/usr/bin/python3

import subprocess

path="test's dir/test's file.txt"
subprocess.run(['cat', path])

或立即:

subprocess.run(['cat', "test's dir/test's file.txt"])

由于

subprocess.run()
函数将命令作为列表, 不是单个字符串(可以使用
shell=True
选项),我们没有 担心命令周围的额外引用。

请注意

subprocess.run()
由 Python 3.5 或更高版本支持。


2
投票

您可以使用此处-doc:

sh -s <<-'EOF'
cat "test's dir/test's file.txt"
EOF

0
投票

此选项避免了两级引用的需要:

sh -c 'cat -- "$0"' "test's dir/test's file.txt"

请参阅如何通过“bash -c”命令使用位置参数?。 (这也适用于

sh -c
。)

© www.soinside.com 2019 - 2024. All rights reserved.