split but keep the separator for few

Viewed 98

I am having a large file which column one is in the following format. There can be 3-6 different id separated by "_"

s1_asd_ucsd
b4_asd_id_vu
c10_id_js_uw
d4_sch_vu

I want to split this column into two column. Column 2 contain the last id and column 1 contain the initial ids; like bellow

s1_asd  ucsd
b4_asd_id   vu
c10_id_js   uw
d4_sch  vu

I know how to print the last column by following; but dont know how to print the previous ids while keeping the separator.

awk '{n=split($1, b, "_"); }{  print b[n]}'
3 Answers

With your shown samples, could you please try following. Written and tested with GNU awk, should work in any awk.

awk 'match($0,/.*_/){print substr($0,RSTART,RLENGTH-1),substr($0,RSTART+RLENGTH)}' Input_file

Simple explanation would be: Using match function of awk to match till last occurrence of _ in each line and then while printing its sub strings printing just before last _ to remove it and then printing rest of the line(along with space between matched part and rest part).

A simple sed solution using greedy matching pattern:

sed -E 's/(.+)_(.+)/\1   \2/' file

s1_asd    ucsd
b4_asd_id    vu
c10_id_js    uw
d4_sch    vu
Related