TopCoder
TopCoder

Reputation: 4296

bash command substitution failing with ( character

I am running a bash script which is as follows :

n=`ls /tmp/abc/*-(2|3).20150406.txt | wc -l`;

but it is giving syntax error at this line saying command substitution: line 1 unexpected token `('

The same command runs fine without the script on console. Am i missing anything here. Any help would be appreciated.

Upvotes: 1

Views: 95

Answers (2)

anubhava
anubhava

Reputation: 785256

You will need to use extglob here to match few chosen numbers like this:

shopt -s extglob
printf "%s\n" /tmp/abc/*-@(2|3|29).20150406.txt

It will print:

/tmp/abc/run-2.20150406.txt
/tmp/abc/run-29.20150406.txt
/tmp/abc/run-3.20150406.txt

To count them:

printf "%s\n" /tmp/abc/*-@(2|3|29).20150406.txt | wc -l

Upvotes: 1

Adam Matan
Adam Matan

Reputation: 136231

Assuming that you would like to match this filename pattern:

<anything><dash><2 or 3><anything><20150406.txt>

For example, matching:

file-2.20150406.txt
file-3.20150406.txt
run-29.20150406.txt

But not:

file-4.20150406.txt
run-29.20150406

The following should do the trick:

#!/bin/bash

n=`find /tmp/abc -regex ".*-[23].*20150406.txt" | wc -l`
echo $n

In general, find is more suitable for regexen than ls.

Upvotes: 1

Related Questions