Search code examples
linuxbashls

How to escape square brackets in a ls output


I'm experiencing some problems to escape square brackets in any file name.

I need to compare two list. The ls output is the first list and the second is the ARQ02.

#!/bin/bash  

exec 3< <(ls /home/lint)  

while read arq <&3; do  
 var=`grep -e "$arq" ARQ02`  
    if [ "$?" -ne 0 ] ; then  
     echo "$arq" >> result  
    fi  
done  

exec 3<&-  

Sorry for my bad english.


Solution

  • Your immediate problem is that you must instruct grep to interpret the search term as a literal rather than a regular expression, using the -F option:

    var=$(grep -Fe "$arq" ARQ02)
    

    That way, any regex metacharacters that happen to be in the output from ls /home/lint - such as [ and ] - will still be treated as literals and won't break the grep invocation.

    That said, it looks like your command could be streamlined, such as by using the output from ls /home/lint directly as the set of search strings to pass to grep at once, using the -f option:

    grep -Ff <(ls /home/lint) ARQ02 > result
    

    <(...) is a so-called process substitution, which, simply put, presents the output from a command as if it were a (temporary) file, which is what -f expects: a file containing the search terms for grep.


    Alternatively, if:

    • the lines of ARQ02 contain only filenames that fully match (some of) the filenames in the output from ls /home/lint, and

    • you don't mind sorting or want to sort the matches stored in result,

    consider HuStmpHrrr's helpful answer.