Operating System - Linux
1751709 Members
4373 Online
108781 Solutions
New Discussion юеВ

filename field extraction

 
SOLVED
Go to solution
Pando
Regular Advisor

filename field extraction

dear gurus,

I have a file with different length and separated by "_". See example of filename below.

aaaa_bb_cc_1111_222222_s1.txt
xxxx_yy_cc_dd_1111_222222_s2.txt

I would like to seek help on how to extract the 1111 and 222222 from the filenames above and put them in a variable.

Maximum points for all correct replies.
4 REPLIES 4
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: filename field extraction


extract()
{
typeset V=${1}
shift
typeset -i XSTAT=0

echo "${V}" | awk -F '_' '{printf("%s_%s\n",$(NF - 2),$(NF - 1))}'
XSTAT=${?}
return ${XSTAT}
} # extract

V1="aaaa_bbb_cc_11111_222222_s1.txt"
XX=$(extract "${V1}")
echo "XX = ${XX}"
If it ain't broke, I can fix that.
Pando
Regular Advisor

Re: filename field extraction

Hi ACS,

the 1111 and 222222 needs to be in a separate variable. thanks!


Pando
Regular Advisor

Re: filename field extraction

Dear ACS,

Thanks for your input!
Nice job!
Howard Marshall
Regular Advisor

Re: filename field extraction

I know the thread is closed and I am not fishing for points any way so.

My suggestion in this case would be to use awk, as Clay did but instead of counting fields I would just use $NF-2 and $NF-1 sense the portions of the file names you want are always going to be 2nd and 3rd from the last.

Might make for a simpler read in the script if you ever have to troubleshoot it.

Howard