Suppose I have a list of csv files with the following format:
INT_V1_<Product>_<ID>_<Name>_<ddmmyy>.csv
ASG_B1_V1_<Product>_<ID>_<Name>_<ddmmyy>.csv
The INT_V1_ & ASG_B1_V1_ is fixed, meaning all the csv files start with it.
How can I split the file names into variable?
For example, I wanted to capture the Name & assign it to a variable $Name
.
Best Answer
With
zsh
:With
bash
4.3 or newer, ksh93t or newer or zsh in sh emulation (though inzsh
, you'd rather simply dofield=("${(@s:_:)field}")
for splitting than using the split+glob non-sense operator ofsh
) you could split the string on_
characters and reference them from the end:Or (bash 3.2 or newer):
(that assumes
$file
contains valid text in the current locale which is not guaranteed for file names unless you fix the locale to C or other locale with a single-byte per character charset).Like
zsh
's*
above, the.*
is greedy. So the first one will eat as many*_
as possible, so the remaining.*
will only match_
-free strings.With
ksh93
, you could doIn a POSIX
sh
script, you could use the${var#pattern}
,${var%pattern}
standard parameter expansion operators:Or use the split+glob operator again: