Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How can I retrieve every portion separately from the following file name?

DSA4020_frontcover_20346501_2011-05.doc

I want to retrieve the information as below:

name = DSA4020
type = frontcover
id =  20346501
date = 2011-05

Is it possible to do this with sed?

share|improve this question
    
Why use sed when you can use cut (or awk) ? –  Isaac Clarke May 26 '11 at 14:13
    
doesn't matter whether cut or awk. I just need those values. please help me out. thanks! –  Himalay May 26 '11 at 14:15
    
See your post in stackoverflow.com –  Prince John Wesley May 26 '11 at 14:26
    
done!! thank you. :) and thanks to @eduffy too –  Himalay May 26 '11 at 14:27

5 Answers 5

up vote 0 down vote accepted

How about this 'sed' recipe.

echo "DSA4020_frontcover_20346501_2011-05.doc"  \
 | sed 's|\([^_]*\)_\([^_]*\)_\([^_]*\)_\([^\.]*\).*|name=\1,type=\2,id=\3,date=\4|'

gives this nice CSV form,

name=DSA4020,type=frontcover,id=20346501,date=2011-05
share|improve this answer

You can use the following to split at every _ after removing the extension:

$ echo "DSA4020_frontcover_20346501_2011-05.doc" | cut -d. -f-1 | cut -d_ -f1
DSA4020

Replace the very last digit by 2, 3, 4 to get the individual value each time.

share|improve this answer

If the number of fields is constant :

for i in 1 2 3 4 5; do  
    VARS[${i}]=$(echo ${yourfilename} | cut -d _ -f${i})
done

Then access ${VARS[i]}...

Alternative :

VARS[${i}]=$(echo ${yourfilename} | awk -v i=${i} -F_ '{print $i}'

And if supported (bash 3+)

for i in {1..5}; do (...)

If you have multiple filenames, just add a for loop to skim through all of them.

share|improve this answer
    
It's only four fields. –  Daniel Beck May 26 '11 at 14:31
    
My test routine was five fields long :P I hope OP's clever enough to understand and correct if needed. –  Isaac Clarke May 26 '11 at 14:36
    
I just noticed, this doesn't remove the file extension either, does it? –  Daniel Beck May 29 '11 at 15:22

Split the filename and store in positional parameters:

set -- $(sed 's/_/ /g' <<< ${filename%.doc})
name=$1
type=$2
id=$3
date=$4
share|improve this answer
    
Doesn't cut the file extension. –  Daniel Beck May 29 '11 at 15:22
    
@Daniel, this part will remove a ".doc" extension: ${filename%.doc} –  glenn jackman May 30 '11 at 0:56
    
Sorry about that, didn't notice it. –  Daniel Beck May 30 '11 at 5:42

Try this:

echo "DSA4020_frontcover_20346501_2011-05.doc" | awk -F '_' '{print " name =" $1 "\n type =" $2 "\n id =" $3 "\n date =" $4 } '

output will be like this:

name = DSA4020
type = frontcover
id = 20346501
date = 2011-05
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.