Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Filenames with spaces in Bash script

  1. Aug 15, 2008 #1
    I get a bunch of input files from a Windows data recorder. It produces file names with spaces everywhere. I am trying to write a script to process these files. This process involves several steps with multiple output files generated. I want to strip off the extension of the input file and use the name with different extensions for the output files.

    Example: I can manually type the file names with ' ' and this works
    for FILE in 'file 1' 'file 2' 'file 3'
    stuff1 < ${FILE}.in > ${FILE}.out1
    stuff2 < ${FILE}.in > ${FILE}.out2

    Example: I try to automatically get filenames
    for FILE in `ls -1 *.in | awk -F. '{ print $1; }'`
    stuff1 < ${FILE}.in > ${FILE}.out1
    stuff2 < ${FILE}.in > ${FILE}.out2
    This fails because FILE contains file 1 file 2 file 3 and so the loop uses just "file" not "file 1".

    Example: I tried to use awk to add ' ' around the file names, something like:
    for FILE in `ls -1 *.in | awk -F. '{ print "\'", $1, "\'"; }'`
    But no matter what I try I get a syntax failure.

    Any ideas?
  2. jcsd
  3. Aug 15, 2008 #2
    Solved: The fix was to use read in a while loop instead of using a for loop. I used variable substition instead of awk to seperate the file name from the extension

    ls -1 *.in | while read FILE
    stuff1 < "${FI}.in" > "${FI}.out1"
    stuff2 < "${FI}.in" > "${FI}.out2"
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?