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
sh -c "cat 'test's dir/test's file.txt'"sh -c 'cat "test's dir/test's file.txt"'sh -c "cat '"'"'test's dir/test's file.txt'"'"'"sh -c 'cat "test\'s\ dir/test\'s\ file.txt"'
and many more ...
But none of them is working.Some help would be really appreciated. Thank you!
You can use here-doc:
sh -s <<-'EOF'
cat "test's dir/test's file.txt"
EOF
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'
[Edit]
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.
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.)