Nicky Mattsson
Nicky Mattsson

Reputation: 3052

Extract number from filename

I'm doing a bash script, which automatically can run simulations for me. In order to start the simulation, this other script need an input, which should be dictated by the name of the folder.

So if I have a folder names No200, then I want to extract the number 200. So far, what I have is

PedsDirs=`find . -type d -maxdepth 1`
for dir in $PedsDirs
do
        if [ $dir != "." ]; then
            NoOfPeds = "Number appearing in the name dir" 
        fi
done

Upvotes: 1

Views: 1274

Answers (2)

Andrea Corbellini
Andrea Corbellini

Reputation: 17751

$ dir="No200"
$ echo "${dir#No}"
200

In general, to remove a prefix use ${variable-name#prefix}; to remove a suffix: ${variable-name%suffix}.


Bonus tip: avoid using find. It introduces many problems, especially when your files/directories contain whitespace. Use bash builtins glob features instead:

for dir in No*/           # Loops over all directories starting with 'No'.
do
    dir="${dir%/}"        # Removes the trailing slash from the directory name.
    NoOfPeds="${dir#No}"  # Removes the 'No' prefix.
done

Also, try to always use quotes around variable names to avoid accidental expansion (i.e. use "$dir" instead of just $dir).

Upvotes: 4

Diego Sevilla
Diego Sevilla

Reputation: 29021

Be careful, as you have to join the = to the variable name in bash. To get just the number, you can do something like:

NoOfPeds=`echo $dir | tr -d -c 0-9`

(that is, delete whatever char that it is not a number). All numbers will be then in NoOfPeds.

Upvotes: 0

Related Questions