Ksh

使用 KSH 從文件名中獲取字元串

  • November 18, 2018

我有一個像“XXAR_CUST_INV_pt_PT_BURST.xml”這樣的文件名。結果我只需要“BURST”。

注意:文件名可以有多個“_”(下劃線)。所以,我需要最後一個下劃線和副檔名“.xml”之前的字元串,其中“BURST”

s="XXAR_CUST_INV_pt_PT_BURST.xml"
BUSRTING='';
source <(sed -r 's/(.*)_([^_]*)[.].*/BUSRTING="\1"/' <<< "${s}")
# Result:
BUSRTING=$(printf '%s' "$BUSRTING" | tr '[a-z]' '[A-Z]')
echo BUSRTING=$BUSRTING"

預期結果是突發的

s="XXAR_CUST_INV_pt_PT_BURST_US.xml"
BUSRTING='';
source <(sed -r 's/(.*)_([^_]*)[.].*/BUSRTING="\1"/' <<< "${s}")
# Result:
BUSRTING=$(printf '%s' "$BUSRTING" | tr '[a-z]' '[A-Z]')
echo BUSRTING=$BUSRTING"

預期結果是美國

BURSTING=${s%.xml}         # cut off extension
BURSTING=${BURSTING##*_}   # cut off anything before the last underscore
typeset -u BURSTING        # make uppercase

引用自:https://unix.stackexchange.com/questions/450428