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

发布于 2025-01-11 04:46:13 字数 469 浏览 0 评论 0原文

我在 test's dir 目录中有一个名为 test's file.txt 的文件。 因此文件路径变成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"' 还有更多... 但它们都不起作用。

I have a file named test's file.txt inside test's dir directory.
So the file-path becomes test's dir/test's file.txt.
I want to cat the content of the file but since the file contains an apostrophe and a space it is giving me hard time achieving that.
I have tried several commands including

  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"'
    and many more ...
    But none of them is working.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

巾帼英雄 2025-01-18 04:46:13

请您尝试一下:

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"])

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

请注意,Python 3.5 或更高版本支持 subprocess.run()

Would you please try:

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

As for the pathname part, it is a concatenation of:

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

If you want to execute the shell command in python, would you please try:

#!/usr/bin/python3

import subprocess

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

or immediately:

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

As the subprocess.run() function takes the command as a list,
not a single string (possible with shell=True option), we do not have
to worry about the extra quoting around the command.

Please note subprocess.run() is supported by Python 3.5 or newer.

时光瘦了 2025-01-18 04:46:13

您可以使用此处-doc:

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

You can use here-doc:

sh -s <<-'EOF'
cat "test's dir/test's file.txt"
EOF
世界等同你 2025-01-18 04:46:13

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

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

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

This option avoids the need for two levels of quoting:

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

See How to use positional parameters with "bash -c" command?. (It applies to sh -c too.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文