Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 cant do it

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

Result:
02152023

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading