I have a directory pointed by g_inboundDir which contains following files:XAI-001-20170709-123456791.pdfYXAI-001-20170709-123456791.pdf001-20170744-123456791.pdfVariable g_filPfix=XAIVariable g_fileExt=.pdfNow I want to pick each file which starts with XAI and process it for this I wrote the following command:for i in `ls ${g_inboundDir}/* | grep -E '^${g_filPfix}-([0-9]{3})-([0-9]{8})-([0-9]{9})${g_fileExt}$' 2>/dev/null`I was hoping to receive only XAI-001-20170709-123456791.pdf file but I am not getting any file.
filtering result of ls command to get only certain file names based on a format
linux;shell;grep
grep -E '^${g_filPfix}-([0-9]{3})-([0-9]{8})-([0-9]{9})${g_fileExt}$'The immediate issue here is that the pattern for grep is wrapped in single quotes, so the shell will not expand the variables g_filPfix and g_fileExt. Replacing the quotes with double-quotes would fix that. (and you don't need the parenthesis in the pattern.)Parsing the output of ls like that may be problematic with filenames that have whitespace or some odd characters. In particular, a filename with a space in the middle would be taken as two file names.If you don't actually need such a strict pattern, you could just processall files with the given prefix and suffix:for f in $dir/$prefix*$suffix ; do     somecmd $fdoneIf you do need the strict pattern, some shells (like Bash, which you probably have on Linux) can do the regex match without external tools. So, to loop over all files in the directory and ignore the files that don't match the pattern:for f in $dir/* ; do     [[ $f =~ /$prefix-[0-9]{3}-[0-9]{8}-[0-9]{9}$suffix$ ]] || continue    somecmd $fdone