HELP with AWK one-liner. Need to employ an If condition inside AWK to check for array variable ?

Hello experts,

I'm stuck with this script for three days now. Here's what i need.
I need to split a large delimited (,) file into 2 files based on the value present in the last field.
Samp: Something.csv

bca,adc,asdf,123,12C
bca,adc,asdf,123,13C
def,adc,asdf,123,12A

I need this split into 2 files with C records in file and the rest in another.
I'm using the below awk :

awk -F, '{if($NF=="12C"||$NF=="13C")print >"splitC.csv";else print >"slitA.csv"}' SOMTHING.csv

This works fine. But i have around 50(or more in the future) different values for C such as 12C, 13C, 18C, 19C, 26C, ... I don't want to hard-code these values with the "||" clause in the above if condition.
Is there a way i can store this in a variable array. or in a variable as a string and manage to check for this condition ??

I tried writing an AWK block, etc to manage this, but to no success.
Please help me on this.

Thanks Gurus!

why don't you use regular expressions? Something like

$NF ~ /.*C$/ { print > "splitC.csv" }
1 Like
awk -F, '$NF ~ /C$/ {print > "splitC.csv";next}1' inputfile > splitother.csv
1 Like

If the values where truly different:

awk -F, -v vA="12C,13C" 'BEGIN{split(vA,a,",");for (i in a){b[a]++}}{fic= $NF in b ? "splitC.csv" : "splitB.csv" ; print $0>>fic}' infile.csv
1 Like

Using the last character in each line...

$ cat Something.csv
bca,adc,asdf,123,12C
bca,adc,asdf,123,13C
def,adc,asdf,123,12A

$ awk '{print substr($0,length)}' Something.csv
C
C
A

$ awk '{print > "split" substr($0,length) ".csv"}' Something.csv

$ head split?.csv
==> splitA.csv <==
def,adc,asdf,123,12A

==> splitC.csv <==
bca,adc,asdf,123,12C
bca,adc,asdf,123,13C

$
1 Like

Splendid, Guys!
I'm going by Klsshxx's way. It works like a charm and fits my requirement like a glove.

116@434 and elixir_sinari's tips are also very helpful.

Thanks for the quick response!!

[root@node2 ~]# sed -n '/C$/!p' infile
def,adc,asdf,123,12A
[root@node2 ~]# sed -n '/C$/p' infile
bca,adc,asdf,123,12C
bca,adc,asdf,123,13C
1 Like