wsdzbm
wsdzbm

Reputation: 3670

Extract missing digits in a sequence

I extracted some digits from files using grep, assuming they are 1 2 3 5 6 11 18. To get the missings ones in 1..20, I put them into files and compare using comm.

a='1 2 3 5 6 11 18'
printf '%d\n' $a | sort -u > 111
printf '%d\n' {1..20} | sort -u > 222
comm 111 222
rm 111 222

which outputs

    1
10
    11
12
13
14
15
16
17
    18
19
    2
20
    3
4
    5
    6
7
8
9

Is there more convenient way without saving to files?

Upvotes: 0

Views: 47

Answers (1)

Andreas Louv
Andreas Louv

Reputation: 47119

You can iterate over the numbers from 1 though 20, and then use a regex to compare each number against a:

a='1 2 3 5 6 11 18'
for i in {1..20}; do
  re="\\b$i\\b"
  [[ "$a" =~ $re ]] || echo "$i"
done

The regex is quite simple: \b is a word boundary, and $i gets expanded to 1, 2, ..., 20

The above will print all numbers that are not in a.

Upvotes: 3

Related Questions