Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract numbers from file names

Tags:

bash

I got a lot of files whose names are like this:

tmp1.csv
tmp32.csv
tmp9.csv
tmp76.csv
...

They are in the same dir, and I want to extract the numbers in the file name. How can I do that in bash?

PS

I tried grep, but can't make it. Also I tried ${filename##[a-z]}. Are they the right way to go?

like image 310
Alcott Avatar asked Dec 10 '22 00:12

Alcott


1 Answers

ls |grep -o "[0-9]\+"

Example:

$ ls *.csv
3tmp44.csv  newdata_write.csv  tmp1.csv  tmp2.csv

$ ls *.csv |grep -o "[0-9]\+"
3
44
1
2

Edit:

From grep man page:

Basic vs Extended Regular Expressions

   In basic regular expressions the meta-characters ?, +, {, |, (, and )  lose  their  special  meaning;  instead  use  the  backslashed
   versions \?, \+, \{, \|, \(, and \).

That is why you need to use \+

like image 151
Facundo Casco Avatar answered Jan 05 '23 00:01

Facundo Casco