Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split but keep the separator for few

Tags:

split

awk

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]}'
like image 232
Ashi Avatar asked Aug 01 '26 05:08

Ashi


2 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).

like image 62
RavinderSingh13 Avatar answered Aug 02 '26 18:08

RavinderSingh13


With GNU awk:

awk 'BEGIN{FS=OFS="_"} {last=$NF; NF--; print $0 "   " last}' file

Save last field, remove last field from current row, output current row, output three spaces and append saved last field.

Output:

s1_asd   ucsd
b4_asd_id   vu
c10_id_js   uw
d4_sch   vu

See: 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR

like image 29
Cyrus Avatar answered Aug 02 '26 18:08

Cyrus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!