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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

string manipulation in ksh 1

Status
Not open for further replies.

SimonSellick

Programmer
Nov 3, 2003
305
GB
Hi,

I am faced with filenames of a format x-CCYYMMDD.csv where x can be anything between 1 and 14 characters, examples:

T001-20050901.csv
XY_AB_12_01-20031231.csv

I need to extract the date string and the preceding code into shell variables. For the two files above, the results should be:

$FILENAME $DATE $CODE
T001-20050901.csv 20050901 T001
XY_AB_12_01-20031231.csv 20031231 XY_AB_12_01

Is there a substring() or equivalent function available in the shell, or in awk; or can anyone suggest another way to achieve this? I can rely on the hyphen separator between code and date, but I can't rely on its being the only one (that is, there might be some in the code section as well).

Any pointers gratefully received.
 
FILENAME="XY_AB_12_01-20031231.csv"
CODE=${FILENAME%-*}
DATE="${FILENAME#*-}";DATE="${DATE%.csv}"
echo "$FILENAME\t$DATE\t$CODE"

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Yes, that's great - thanks PHV.

Now all I need to do is work out why it works!
 
Hi

SimonSellick said:
I can rely on the hyphen separator between code and date, but I can't rely on its being the only one

Code:
FILENAME="with-more-dashes-20031231.csv"
eval `echo "$FILENAME" | sed 's/\(.*\)-\([^-]*\)/CODE="\1";DATE="\2"/'`
echo -e "$FILENAME\t$DATE\t$CODE"

Feherke.
 
OK, replace this:
DATE="${FILENAME#*-}";DATE="${DATE%.csv}"
By this:
DATE="${FILENAME##*-}";DATE="${DATE%.csv}"

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
OK, got it (found the ksh man page once you'd shown me what to look for). And the ## matches the longest possible string before the terminating hyphen, rather than just up to the first one.

Clever stuff.

Thanks again both.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top