Я хочу написать гибкое регулярное выражение для grep
, которое будет возвращать поисковые термины, найденные на определенном расстоянии друг от друга.
Идеальное поведение - это что-то вроде исследовательских баз данных;например, где вы можете искать статьи, которые имеют capital
и GDP
в пределах 15 слов друг от друга, в том числе статьи, в которых строки capital
и GDP
могут быть разделены на пять, шесть, семь и т. д.., буквенно-цифровые строки неопределенной длины.Оператор регулярного выражения будет включать знаки препинания (например, запятые, точки, дефисы), а также знаки ударения и диакритические знаки.Таким образом, результаты, в которых chechè
и lavi
находятся на расстоянии не более пяти строк.
Я полагаю, что в этом заявлении будут использоваться заглядывания и фразы типа {1,15}
, или, возможно, передача одного grep
через другой grep
, но это теряет выгоду GREP_OPTIONS='--color=auto'
.Построение этого действительно вне моего набора навыков.У меня есть набор документов .txt, по которым я хочу выполнить поиск, но сделать регулярное выражение гибким для изменения расстояния между строками или усечения терминов также было бы полезно для других, у которых есть такие вещи, как полевые заметки или чтение заметок в стандарте.формат.
РЕДАКТИРОВАТЬ
Ниже приведен пример отрывков, взятых из Библии.
Ye shall buy meat of them for money, that ye may eat; and ye shall also buy water of them for money, that ye may drink. For the Lord thy God hath blessed thee in all the works of thy hand: he knoweth thy walking through this great wilderness: these forty years the Lord thy God hath been with thee; thou hast lacked nothing... Thou shalt sell me meat for money, that I may eat; and give me water for money, that I may drink: only I will pass through on my feet: (as the children of Esau which dwell in Seir, and the Moabites which dwell in Ar, did unto me:) until I shall pass over Jordan into the land which the Lord our God giveth us. But Sihon king of Heshbon would not let us pass by him: for the Lord thy God hardened his spirit, and made his heart obstinate, that he might deliver him into thy hand, as appeareth this day. And the Lord said unto me, Behold, I have begun to give Sihon and his land before thee: begin to possess, that thou mayest inherit his land. Then Sihon came out against us, he and all his people, to fight at Jahaz. And the Lord our God delivered him before us; and we smote him, and his sons, and all his people. And if the way be too long for thee, so that thou art not able to carry it; or if the place be too far from thee, which the Lord thy God shall choose to set his name there, when the Lord thy God hath blessed thee: then shalt thou turn it into money, and bind up the money in thine hand, and shalt go unto the place which the Lord thy God shall choose: and thou shalt bestow that money for whatsoever thy soul lusteth after, for oxen, or for sheep, or for wine, or for strong drink, or for whatsoever thy soul desireth: and thou shalt eat there before the Lord thy God, and thou shalt rejoice, thou, and thine household, and the Levite that is within thy gates; thou shalt not forsake him: for he hath no part nor inheritance with thee... Now it came to pass, that at what time the chest was brought unto the king’s office by the hand of the Levites, and when they saw that there was much money, the king’s scribe and the high priest’s officer came and emptied the chest, and took it, and carried it to his place again. Thus they did day by day, and gathered money in abundance. And when they had finished it, they brought the rest of the money before the king and Jehoiada, whereof were made vessels for the house of the Lord , even vessels to minister, and to offer withal, and spoons, and vessels of gold and silver. And they offered burnt offerings in the house of the Lord continually all the days of Jehoiada. Thou hast bought me no sweet cane with money, neither hast thou filled me with the fat of thy sacrifices; but thou hast made me to serve with thy sins, thou hast wearied me with thine iniquities... Howbeit there were not made for the house of the Lord bowls of silver, snuffers, basins, trumpets, any vessels of gold, or vessels of silver, of the money that was brought into the house of the Lord: but they gave that to the workmen, and repaired therewith the house of the Lord. Moreover they reckoned not with the men, into whose hand they delivered the money to be bestowed on workmen: for they dealt faithfully. The trespass money and sin money was not brought into the house of the Lord: it was the priests’.
Если бы я хотел найти примеры, гдеshalt
и money
присутствуют в пяти словах (включая знаки препинания), как бы я написал это регулярное выражение?
Я не уверен, как получить ожидаемые результаты, поскольку grep --context=1
будет включать в себя болеетолько строки с 0-5 строками между ними, но я предполагаю, что результаты идентифицируют:
shalt sell me meat for money
shalt thou turn it into money
money in thine hand, and shalt
shalt bestow that money
Но не вернут shall buy meat of them for money,
, поскольку в качестве шестой строки отображается «деньги».