rodee
rodee

Reputation: 3171

How to get the wildcard matched portion from a filename

for name in file*.txt
do
   echo ${name%.txt} | grep -o -E '[0-9]+'
done

is there a better way then using grep? I have file1.txt, file2.txt ...., want to extract just the numbers.

Upvotes: 0

Views: 26

Answers (2)

James Brown
James Brown

Reputation: 37424

In bash:

$ for f in test* ; do f=${f#test} ; echo "${f%.txt}" ; done
1
2
3

Add some quotes if filenames have space in them.bb

Using GNU awk:

$ awk 'BEGINFILE {
    gsub(/^test|\.txt/,"",FILENAME)
    print FILENAME
    nextfile
}' test*
1
2
3

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295650

If your shell is bash, you might also consider replacing all non-numeric characters with the empty string with a parameter expansion, as follows:

for name in file*.txt; do
  echo "${name//[![:digit:]]/}"
done

By contrast, if you need to work with POSIX-compatible shells (and the file prefix is hardcoded), consider trimming prefix and suffix using the following POSIX-compliant PEs:

for name in file*.txt; do
   num=${name%.txt}; num=${num#file}
   echo "$num"
done

Upvotes: 1

Related Questions