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".
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityHow 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".
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.
-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
...).
Jan 30, 2018 at 16:19
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.
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
join
doesn't check for a numeric sort. For example a file containing 1\n100\n11\n
is reported to be sorted.
Jan 30, 2018 at 23:18