Search code examples
foreachlscsh

C-shell : foreach ls cannot detect file name with dash/hyphen (-)


I have a c shell script that filter for a file with condition as below:

*_[+-]*[A-D]*.txt

Example of file:

Reflow_-12_A124er.txt

My script as below:

#!/bin/csh -f

cd /data
foreach file (`ls *_[+-]*[A-D]*.txt`)
echo "file: " $file
gzip $file
end 

If i try command ls *_[+-]*[A-D]*.txt in data folder, there is output for the txt file. But if i try run the script, the script not detect the file with (-) even tough it meets the filter. Why?


Solution

  • I honestly don't understand why, but this works:

    foreach file (`ls *_[+--]*[A-D]*.txt`)
    

    And so does this:

    foreach file (`ls *_[--+]*[A-D]*.txt`)
    

    You would think I'm accidentally including the , character that rests between + and - on the ASCII table, right? Nope. The script didn't pick up my example file, Reflow_,77D123ab.txt.

    The documentation for csh clearly states that putting the dash at the beginning of the character class will represent a literal dash (and also that some versions of csh accept the dash at the end), but maybe it's a bug to do with + being a quantifier, or it just needs more than 2 characters in the character class to work properly.