Note that there are some explanatory texts on larger screens.

plurals
  1. POBash and filenames with spaces
    text
    copied!<p>The following is a simple Bash command line:</p> <pre><code>grep -li 'regex' "filename with spaces" "filename" </code></pre> <p>No problems. Also the following works just fine:</p> <pre><code>grep -li 'regex' $(&lt;listOfFiles.txt) </code></pre> <p>where <code>listOfFiles.txt</code> contains a list of filenames to be grepped, one filename per line.</p> <p>The problem occurs when <code>listOfFiles.txt</code> contains filenames with embedded spaces. In all cases I've tried (see below), Bash splits the filenames at the spaces so, for example, a line in <code>listOfFiles.txt</code> containing a name like <code>./this is a file.xml</code> ends up trying to run grep on each piece (<code>./this</code>, <code>is</code>, <code>a</code> and <code>file.xml</code>).</p> <p>I thought I was a relatively advanced Bash user, but I cannot find a simple magic incantation to get this to work. Here are the things I've tried.</p> <pre><code>grep -li 'regex' `cat listOfFiles.txt` </code></pre> <p>Fails as described above (I didn't really expect this to work), so I thought I'd put quotes around each filename:</p> <pre><code>grep -li 'regex' `sed -e 's/.*/"&amp;"/' listOfFiles.txt` </code></pre> <p>Bash interprets the quotes as part of the filename and gives "No such file or directory" for each file (and <em>still</em> splits the filenames with blanks)</p> <pre><code>for i in $(&lt;listOfFiles.txt); do grep -li 'regex' "$i"; done </code></pre> <p>This fails as for the original attempt (that is, it behaves as if the quotes are ignored) and is very slow since it has to launch one 'grep' process per file instead of processing all files in one invocation.</p> <p>The following works, but requires some careful double-escaping if the regular expression contains shell metacharacters:</p> <pre><code>eval grep -li 'regex' `sed -e 's/.*/"&amp;"/' listOfFiles.txt` </code></pre> <p>Is this the only way to construct the command line so it will correctly handle filenames with spaces?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload