7

How to check if numbers from list file are increasing?

Example list1:

658
659
663

will get "OK".

Example list2:

658
664
663

will get "FAIL".

Example list3:

23
24
25
26

will get "OK".

2
  • 3
    Might be able to just run sort -nc... – Jeff Schaller Jan 30 '18 at 13:08
  • need to get expected output ok/fail – jango Jan 30 '18 at 13:13
13

You can use sort -nc filename to validate if the file is in incremental order or not (containing numbers only).

sort -n -c filename >/dev/null 2>&1 && echo "OK" || echo "FAIL"

Or in short (note the upper -C "like -c, but do not report first bad line"), also using -u option to check for a strictly ascending order as well as -g option to have more number formats to be supported (like +2, 0x10, 1.2e+3, infinity, ... ) suggested by @StéphaneChazelas:

sort -guC filename && echo "OK" || echo "FAIL"

Note: if you don't want report "FAIL" on the repeated same numbers, omit the -u option at above.

2
  • You can also add a -u option to check for a strictly ascending order (like in Raman's approach). See also the -g option with GNU sort for more number formats to be supported (like +2, 0x10, 1.2e+3, infinity...). – Stéphane Chazelas Jan 30 '18 at 16:19
  • thank you, I have included your comment in my answer. – αғsнιη Jan 30 '18 at 17:37
8
awk 'BEGIN {res = "OK"}
     NR > 1 && $1 <= prev {res = "Fail"; exit}
     {prev = $1}
     END {print res}'  file

This awk solution should work. Set the res variable to OK from the outset and then check the first space delimited field in the file against the prev variable. If this line's $1 is less than the previous, set res to Fail and stop reading. Finally at the end of the script, print the res variable.

4
  • I get fail on that 1234 1235 1236 – jango Jan 30 '18 at 13:20
  • Hmmmm,works fine for me, – Raman Sailopal Jan 30 '18 at 13:47
  • This would fail on a correctly ascending negative series like -3 -2 -1 (not sure whether that matters to the OP). – Kusalananda Jan 30 '18 at 13:48
  • 2
    @Kusalananda, I took the liberty to fix that part. – Stéphane Chazelas Jan 30 '18 at 16:26
3

Another trick with join command:

join --check-order file file &>/dev/null && echo "OK" || echo "FAIL"

Tests:

$ cat a1
11
33
22
$ join --check-order a1 a1 &>/dev/null && echo "OK" || echo "FAIL"
FAIL

$ cat a2
11
22
33
$ join --check-order a2 a2 &>/dev/null && echo "OK" || echo "FAIL"
OK
1
  • 1
    Nice idea, but watch out - join doesn't check for a numeric sort. For example a file containing 1\n100\n11\n is reported to be sorted. – Digital Trauma Jan 30 '18 at 23:18

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.