I have a file with the lines as:
5 3 6 4 2 3 5
1 4 3 2 6 5 8
..
I want to get the min on each line, so for example with the input given above, I should get:
min of first line: 2
min of second line: 1
..
How can I use awk to do this for any arbitrary number of columns in each line?
Your problem is pretty simple. All you need to do is to define a variable
min
in theBEGIN
part of your script, and at each line, you just have to perform a simple C-like algorithm for minimum element (set the first field asmin
, and then perform a check with the next field, and so on until you reach the final field of the line). The total number of fields in the line will be known to you because of the variable NF. So its just a matter of writing a for loop. Once the for loop is fully executed for the line, you will have the minimum element with you, and you could just print it.If you don't mind the output using digits instead of words you can use this one liner:
If you really do want to count in ordinal numbers:
Save this to
script.awk
and run like:Obviously this will only work for files with upto 4 lines but just increase the ordinal numbers list to the maximum number you think you will need. You should be able to find a list online pretty easily.