Search code examples
bashawksedcut

extract chars from each line in specified order


I want to extract Nth character with specific order using bash command.

For example,if sample.txt contains strings like below..

ABCDEFG
ABCDEFG
ABCDEFG
ABCDEFG

And my desired output is below.

BDC
BDC
BDC
BDC

But, when i use cut -c 2,4,3 < sample.txt, I got,

BCD
BCD
BCD
BCD 

How can I preserve the order that I give? Is there any other command or script for this action?


Solution

  • In some popular AWKs*, when field separator is the null string, each individual character becomes a field. Using this functionality you can easily extract selected characters in any order. E.g.:

    $ awk -v FS= '{print $2$4$3}' file
    BDC
    BDC
    BDC
    BDC
    

    * Like GAWK, MAWK, busybox AWK, OpenBSD AWK, etc.