Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Extracing values from a file name using tokening and using values in a text file -is this possible? 1

Status
Not open for further replies.

bazil2

Technical User
Feb 15, 2010
148
DE
(Elementary user)

Please consider the following example files:

12345_apple_small_red_40.jpg
98765_pear_big_green_50.jpg

The file name contains information (tokens) that describes the JPG image like this:

Image Number_Fruit type_Size_Colour_Weight

Each segments is separated by an underscore '_', let's call this my token separator.

The goal is to run a script that will read each file name and extract each token to build a text file, say XML.

Would it be possible to create such a script that would do this?

Best regards
 
Hi

Keeping it simple for now :
Code:
[navy]master #[/navy] ls
12345_apple_small_red_40.jpg  98765_pear_big_green_50.jpg

[navy]master #[/navy] tag=( 'image_number' 'fruit_type' 'color' 'size' 'weight' )

[navy]master #[/navy] (
[navy]>[/navy] echo '<data>'
[navy]>[/navy] for name in *.jpg; do
[navy]>[/navy]   IFS='_' read -ra part <<< "${name%.jpg}"
[navy]>[/navy]   echo '  <item>'
[navy]>[/navy]   for i in "${!tag[@]}"; do
[navy]>[/navy]     echo "    <${tag[i]}>${part[i]}</${tag[i]}>"
[navy]>[/navy]   done
[navy]>[/navy]   echo '  </item>'
[navy]>[/navy] done
[navy]>[/navy] echo '</data>'
[navy]>[/navy] ) > bazil.xml

[navy]master #[/navy] cat bazil.xml 
<data>
  <item>
    <image_number>12345</image_number>
    <fruit_type>apple</fruit_type>
    <color>small</color>
    <size>red</size>
    <weight>40</weight>
  </item>
  <item>
    <image_number>98765</image_number>
    <fruit_type>pear</fruit_type>
    <color>big</color>
    <size>green</size>
    <weight>50</weight>
  </item>
</data>
Tested with Bash, MKsh ( not traditional Ksh ).

Feherke.
feherke.ga
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top