1

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?

3
  • Why use sed when you can use cut (or awk) ? May 26, 2011 at 14:13
  • doesn't matter whether cut or awk. I just need those values. please help me out. thanks!
    – Himalay
    May 26, 2011 at 14:15
  • See your post in stackoverflow.com May 26, 2011 at 14:26

5 Answers 5

1

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
0

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.

0

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.

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

Split the filename and store in positional parameters:

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .