Linux – How to pass a file or folder containing whitespace as an argument to a command-line program in a GNU/Linux or Cygwin environment

bashcommand linecygwin;linuxshell

There are occasions when you are working with files and folders that contain spaces in them. The problem is any time you try and pipe files / folders containing whitespace to another command-line program, the files / folders containing whitespace are interpreted as separate arguments rather than as a single argument. For example, consider the following directory tree:

Folder With Spaces
Folder With Spaces/FolderWithoutSpaces
Folder With Spaces/FolderWithoutSpaces/file with spaces.txt
FolderWithoutSpaces
FolderWithoutSpaces/fileWithoutSpaces.txt

If you try and run a shell command such as "grep 'some text' $(find . -type f)", you'll get the following output:

grep: ./Folder: No such file or directory
grep: With: No such file or directory
grep: Spaces/FolderWithoutSpaces/file: No such file or directory
grep: with: No such file or directory
grep: spaces.txt: No such file or directory

The big question is, how do you pipe files / folders that have whitespace in them as arguments to a command line program?

Best Answer

You would be better off using the -exec action (option) of find and quoting your arguments.

Example:

find . -type f -exec grep stuff '{}' \;

The quotes will keep the spaces from being interpreted and you don't have to pipe everything through xargs unnecessarily.

From the find man page:

-exec command ;

    Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of  ‘;’  is encountered. The string  ‘{}’  is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find.  Both of these constructions might need to be escaped (with a  ‘\’) or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory.

    There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead.

Related Question