-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?

5
  • Only Bash or is awk usable? Commented Apr 25, 2015 at 18:34
  • It will be OK for me if it returns the desired output and compatible to use in shell script. Commented Apr 25, 2015 at 18:38
  • x="ABC_DE_FGHI_10_JK_LMN.csv"; x=${x#*_*_*_}; echo ${x%_*_*} Commented Apr 25, 2015 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. Commented Apr 25, 2015 at 19:53
  • Using _ or . as separator: x="ABC_DE_FGHI_10.csv"; x=${x#*[_.]*[_.]*[_.]}; echo ${x%[_.]*} Commented Apr 25, 2015 at 22:46

1 Answer 1

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}'
Sign up to request clarification or add additional context in comments.

2 Comments

What if ID comes at last position in file-name? Ex. echo 'ABC_DE_FGHI_10.csv' | awk -F_ -v pos=4 '{print $pos}' then here it returns 10.csv instead of 10
@PRATIKPATIL Then add it to the delimiter (See edit).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.