I have a file with below data:


I want to check each value in column 5(delimiter to get column 5 is ","). Compare the same with column 6 and get the least difference element into the new file.

Expected output is:


My file has more than 200 rows, looking for a one liner command to do the same.

  • 4
    Your name is 'programmer'... well what have you 'programmed' on your own so far? Where are you stuck? – Panki Mar 14 at 9:04
  • 1
    I cooked up a oneline solution, but it's in python and the tags state bash. – Panki Mar 14 at 9:16
  • 1
    @Panki please don't post answers as comments. – terdon Mar 14 at 9:34
  • 1
    @Panki if it's a one-liner, then sure, you may as well. – terdon Mar 14 at 9:38
  • 1
    Yes it needs to process the file line by line. I don't really know what other solution there would be. – Panki Mar 14 at 9:45

Here is my Python solution.

with open('/path/to/file', 'r') as f:
    for line in f:
        print(','.join(x[:4]) + ',' + str(min(y, key=lambda z: abs(float(z)-float(x[5])))))

If you have something like Pyed Piper, also known as pyp, you can run this straight from the terminal prompt: https://code.google.com/archive/p/pyp/

  • Thanks for the share. I am able to get the desired result with this. – Programmer Mar 14 at 10:08

As an AWK solution is requested, I will give one.

awk -F, 'NF>4{
        print $1","$2","$3","$4","l                                                                                                                                                                                
}' input > output
  • 1
    +1, clever use of ^2 to get around the absence of an abs function in awk – iruvar Mar 15 at 19:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.