Reputation: 111
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
Upvotes: 6
Views: 158
Reputation: 36725
Ex:
echo FT0215202301.xml | cut -b 7-10,5-6,3-4
Result:
02152023
Expected:
20230215
Observe that your command preserved order, which is logical considering cut
does
remove sections from each line of files
Therefore your task is beyond what cut
can do, as this would require to rearrange elements. If you wish to use awk
to work with characters you might set field separator (FS
) to empty string and access 1st character using $1
, 2nd character using $2
, 3rd character using $3
and so on. In this case you might do
echo FT0215202301.xml | awk 'BEGIN{FS=""}{print $7$8$9$10$3$4$5$6}'
gives output
20230215
(tested in GNU Awk 5.1.0, I am unable to test in aixawk so please try it yourself and write if it does work)
Upvotes: 0
Reputation: 133730
With GNU awk
match
function and its capability of using capturing groups into an array, one could try following code. Using regex ^.{2}(.{4})(.{4}).{2}\.xml$
which creates 2 capturing groups and save values into array named arr
. which we are using to print the values as per requirement.
echo FT0215202301.xml |
awk '
match($0,/^.{2}(.{4})(.{4}).{2}\.xml$/,arr){
print arr[2] arr[1]
}
'
Upvotes: 3
Reputation: 35256
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
Upvotes: 5
Reputation: 36391
I'd use Bash's substring expansion:
f=FT0215202301.xml; echo "${f:6:4}${f:2:2}${f:4:2}"
20230215
Upvotes: 4