Saturday, August 27, 2011

Shell Expansion

This friday, my friend was developing a shell script in KSH for AIX. In this script, several files with a special naming convention should be selected, but only part of the name should be considered. The format is:
word1-word2-extension-serial1-serial2-name.cmt
Where:
word1: any length
word2: any length 
extension: any length 
serial1: 6 chars 
serial2: 6 chars 
name: any length
So, these name would be ok, for instance:
CONTAB1-PALAVRA2-NMT-123456-123456-gilberto.cmt 
CTB1-PLV2-XYZ-654321-000001-joaozinho.cmt
From those names, everything before the serials should be extracted. That is:
CONTAB1-PALAVRA2-NMT 
CTB1-PLV2-XYZ
At first, the nightmare are the 3 variable length parts and the NAME , which is also variable. But SHELL EXPANSION can beat it. And the best, not only BASH, but it does apply to KSH (I really didn't know that !!!).

So, the solution:
$ var='CONTAB1-PALAVRA2-NMT-123456-123456-gilberto.cmt' 
$ echo ${var%%-??????-??????-*.cmt} 
CONTAB1-PALAVRA2-NMT
The second example:
$ var='CTB1-PLV2-XYZ-654321-000001-joaozinho.cmt' 
$ echo ${var%%-??????-??????-*.cmt} 
CTB1-PLV2-XYZ
Once again, the apparently cryptographic hieroglyphic SHELL did it!!!

:D

No comments: