Как отмечалось в другом месте, bash, вероятно, не лучший инструмент для этой работы, вероятно, это проще сделать в Perl или awk. Тем не менее:
#! /bin/bash
print() {
# "${array[*]}" joins the elements with the first characters of IFS as separator
# so we set IFS to the empty string so that the elements are simply concatenated
local IFS=
if (( end - start > 1 )) # more than two consecutive numbers, concatenate
then
printf "%s-%s\t%s\n" "$start" "$end" "${chars[*]}"
elif (( start == end )) # single number, nothing special
then
printf "%s\t%s\n" "$start" "${chars[0]}"
elif (( end - start == 1 )) # two consecutive numbers, print separately
then
printf "%s\t%s\n" "$start" "${chars[0]}" "$end" "${chars[1]}"
fi
}
# An initial read
read -r n a
chars=( "$a" )
start=$n
end=$n
while read -r n a
do
if (( n - end == 1 )) # consecutive numbers, store for printing
then
chars+=( "$a" )
end=$n
continue # move to next line
fi
print # Break in numbers, print stored set
chars=( "$a" ) # reset variables
start=$n
end=$n
done
print # print last set
Если вам не нужны другие строки, вы можете удалить блоки elif
в функции print
.
Пример вывода:
14 R
16 I
21-24 BCQE
33 R
34 L
41 K
62-64 FFM
88 B