Maybe I didn't understand what you're trying to do. I thought the Col_n
was supposed to cause the following lines up to the next Col_n
line to be sorted in increasing alphanumeric order based on the nth character in the line.
Unfortunately, with the sample data given, there is no way to tell if you're trying to sort on the whole line or on the nth character since the results would be the same. If you are trying to sort on the nth character, rdrtx1's script won't do that. Assuming that there aren't any spaces or tabs in your input file (at least not before the character position that is to be sorted), the following might work:
awk '
function finish() {
if(sc != "") close(sc)
}
/^Col_/ {
finish()
print
col = substr($0, 5)
sc = sprintf("sort -k1.%d,1.%d", col, col)
next
}
{ print | sc
}
END { finish()
}' File1.txt
If your input file contains:
Col_1
SW_MH2_ST
ST_F72_9S
SW_MH3_S6
Col_10
SW_MH3_AS7
ST_S15_9CH
SW_MH3_AS8
SW_MH3_ST
Col_5
ST_M93_SZ
ST_C16_TC
Col_4
Abc4123
Cde3234
Bcd2345
Def1234
rdrtx1's script will produce:
Col_1
ST_F72_9S
SW_MH2_ST
SW_MH3_S6
Col_10
ST_S15_9CH
SW_MH3_AS7
SW_MH3_AS8
SW_MH3_ST
Col_5
ST_C16_TC
ST_M93_SZ
Col_4
Abc4123
Bcd2345
Cde3234
Def123
while the script above will produce:
Col_1
ST_F72_9S
SW_MH2_ST
SW_MH3_S6
Col_10
SW_MH3_ST
SW_MH3_AS7
SW_MH3_AS8
ST_S15_9CH
Col_5
ST_C16_TC
ST_M93_SZ
Col_4
Def1234
Bcd2345
Cde3234
Abc4123
If there are spaces in your input file, you need to specify a field separator in the sort command naming a character that can never appear in your input file. If there are tabs in the input file and you want to sort based on output line positions (rather than input character counts), you would have to expand input tabs to a variable number of spaces depending on where in the input line the tab(s) appear. And if you want to sort on output print positions and there are backspace characters in the input, you will need to give a much clearer explanation of what is supposed to happen.
If you want to try the above awk
script on a Solaris/SunOS system, change awk
to /usr/xpg4/bin/awk
, /usr/xpg6/bin/awk
, or nawk
.