octavian octavian - 1 year ago 97
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?

Answer Source

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}'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download