linuxbashshelloperating-systemcat

How to handle single quote/ apostrophe and space together in linux cat command?


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.

Solution

  • 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.