Я думаю, что решение steeldriver с помощью sort является лучшим, хотя, если вы хотите попробовать что-то еще, проверьте следующий скрипт Python:
#!/usr/bin/python2
import re
def checking():
if not check_list:
result.append(list_of_lines[index - 1])
with open('/path/to/the/file') as f:
list_of_lines = f.readlines()
result = []
for index in range(1, len(list_of_lines)):
regex_current = re.search('^[0-9]_[0-9]+', list_of_lines[index])
regex_previous = re.search('^[0-9]_[0-9]+', list_of_lines[index - 1])
check_list = [x for x in result if x.split()[0] == regex_previous.group()]
if regex_current == regex_previous:
checking()
else:
checking()
print ''.join(result)