User1234141414
User1234141414

Reputation: 71

Sort field separator problem in external awk call if its semicolon

I have one csv semicolon separated and I want to sort some field without the header keeping the header untouched. If I use colon as field separator don`t have problem to do, but don´t know to do this with semicolon as field separator.

file temp2:

a,b,c,d,e
1,2,3,4,5
3,1,2,3,1
2,3,1,2,3

>cat temp2 | awk 'NR==1; NR > 1 {print $0 | "sort -t, -k2"}'

result ok sorting field 2:

a,b,c,d,e
3,1,2,3,1
1,2,3,4,5
2,3,1,2,3

Next try, do the same but the semicolon field separator:

file temp1

a;b;c;d;e
1;2;3;4;5
3;1;2;3;1
2;3;1;2;3


 >cat temp1 | awk 'NR==1; NR > 1 {print $0 | "sort -t=";" -k2"}'  

result the file its untouched:

a;b;c;d;e
1;2;3;4;5
2;3;1;2;3
3;1;2;3;1  

The result expected:

a;b;c;d;e
3;1;2;3;1
1;2;3;4;5
2;3;1;2;3

Upvotes: 1

Views: 205

Answers (1)

Ed Morton
Ed Morton

Reputation: 203995

You don't need awk for this:

$ head -n 1 file; tail -n +2 file | sort -t';' -k2
a;b;c;d;e
3;1;2;3;1
1;2;3;4;5
2;3;1;2;3

Having said that, this inside your awk command:

"sort -t=";" -k2"

means this:

("sort -t=") ; (" -k2")

i.e. your nested double quotes are actually terminating the string that you want to use for sorting inside the command. There's also an error where you're using -t=";" instead of -t";" so let's assume that's fixed. Now:

You would use this instead:

"sort -t\";\" -k2"

or even better wrt shell quoting rules:

"sort -t\047;\047 -k2"

wrt your comment below about it not working in awk, look:

$ awk 'NR==1; NR>1{print | "sort -t\047;\047 -k2"}' file
a;b;c;d;e
3;1;2;3;1
1;2;3;4;5
2;3;1;2;3

Upvotes: 1

Related Questions