-1

Suppose I have a file with a name ABC_DE_FGHI_10_JK_LMN.csv. I want to extract the ID from the file-name i.e. 10 with the help of ID position and file-name separator. I have following two inputs

File-name_ID_Position=4; [since 10 is at fourth position in file-name]
File-name_Delimiter="_";

Here ID can be numeric or alpha-numeric. So how extract the 10 from above file with the help of above two inputs. How to achieve this in bash?

Pratik Patil
  • 3,662
  • 3
  • 31
  • 31
  • Only Bash or is awk usable? – dawg Apr 25 '15 at 18:34
  • It will be OK for me if it returns the desired output and compatible to use in shell script. – Pratik Patil Apr 25 '15 at 18:38
  • `x="ABC_DE_FGHI_10_JK_LMN.csv"; x=${x#*_*_*_}; echo ${x%_*_*}` – Cyrus Apr 25 '15 at 19:41
  • @Cyrus, PRATIK PATIL changed the file naming convention, and why I deleted my answer, so `x="ABC_DE_FGHI_10.csv"; x=${x#*_*_*_}; echo ${x%_*_*}` returns `10.csv` not just `10` which he wants. However with this marked as a duplicate I guess it doesn't really matter. – user3439894 Apr 25 '15 at 19:53
  • Using `_` or `.` as separator: `x="ABC_DE_FGHI_10.csv"; x=${x#*[_.]*[_.]*[_.]}; echo ${x%[_.]*}` – Cyrus Apr 25 '15 at 22:46

1 Answers1

2

Instead of writing a regex in bash, I would do it with awk:

echo 'ABC_DE_FGHI_10_JK_LMN.csv' | awk -F_ -v pos=4 '{print $pos}'

or if you want the dot to also be a delimiter (requires GNU awk):

echo 'ABC_DE_FGHI_10_JK_LMN.csv' | awk -F'[_.]' -v pos=4 '{print $pos}'
user000001
  • 32,226
  • 12
  • 81
  • 108