unixawkaixcut

How to cut ranges from end to start?


I need to change the order of a string in AIX, but with the command cut I can't do it

Ex: echo FT0215202301.xml | cut -b 7-10,5-6,3-4

Result: 02152023

Expected: 20230215


Solution

  • A couple ideas using awk or sed:

    $ echo FT0215202301.xml | awk '{print substr($1,7,4) substr($1,3,4)}'
    20230215
    
    $ echo FT0215202301.xml | sed -E 's/^..(....)(....).*/\2\1/'
    20230215
    

    Same solutions but using a here string to eliminate the subshell:

    $ awk '{print substr($1,7,4) substr($1,3,4)}' <<< 'FT0215202301.xml'
    20230215
    
    $ sed -E 's/^..(....)(....).*/\2\1/' <<< 'FT0215202301.xml'
    20230215
    

    If the filename is stored in a variable then you can use bash's substring capability (${var:start:length}) and eliminate the need for other binaries (eg, awk, sed), eg:

    $ fname=FT0215202301.xml
    $ echo "${fname:6:4}${fname:2:4}"
    20230215
    

    NOTE: bash string indexing starts at position 0


    While the above solutions generate OP's expected output of 20230215, OP's cut -b 7-10,5-6,3-4 would seem to indicate OP may want 20231502 as the expected output. If this is the case the modified commands would be:

    $ awk '{print substr($1,7,4) substr($1,5,2) substr($1,3,2)}' <<< 'FT0215202301.xml'
    20231502
    
    $ sed -E 's/^..(..)(..)(....).*/\3\2\1/' <<< 'FT0215202301.xml'
    20231502
    
    $ fname=FT0215202301.xml
    $ echo "${fname:6:4}${fname:4:2}${fname:2:2}"
    20231502