octavian octavian - 3 months ago 6x
Bash Question

Use awk/sed to delete everything after and including third comma on each line

I have a file with lines like this one:

A, B, C, D, E

From that, I would like to obtain:

A, B, C

Can I use sed or awk for this?


Yes, you can:

 sed -r 's/([^,]+,)([^,]+,)([^,]+).*/\1\2\3/'

If you want to keep more than three fields, something along these lines might be better:

sed -r 's/(([^,]+,){2}([^,]+)).*/\1/'

With awk, you could do:

awk -v OFS=',' -F, '{NF=3; print}'