Reputation: 23
I'm filtering a text file with numbers and names I want to print only the lines that contain sets of three sequential consecutive digits. The input list:
123 321 567 765 124 5689 12345.
The output should contain:
123 321 567 765 12345
I have tried this command
awk ' {split ("", N) # delete array N
L = 1 # initialize boolean L to TRUE
for (i=1; i<=length($1); i++){ # for each digit
P = substr($1, i, 1)
if (N[P-1] || N[P+1]){ # if contiguous digit exists,
L = 0 break # set L to FALSE; and quit the for loop
} N[P] = 1 } } L ' file
but it is not working as intended.
I like any sed
or grep or awk
command to work with.
Upvotes: 2
Views: 768
Reputation:
This is the basic regex for 3 sequential (ascending or descending) numbers.
(?:012|123|234|345|456|567|678|789)|(?:987|876|765|654|543|432|321|210)
https://regex101.com/r/hd5PzR/1
You can decorate it with \d*(?:(?:012|123|234|345|456|567|678|789)|(?:987|876|765|654|543|432|321|210))\d*
if needed.
https://regex101.com/r/hd5PzR/2
Upvotes: 2
Reputation: 2794
Are you looking for help on homework or are you trying to solve a problem? If the latter is the case, using an algorithmic approach when there are so few combinations is like using a chain saw to cut butter. Consider the following script:
mystring="012 123 234 567 678 789"
revstring=$(echo $mystring|rev)
checkstring="$mystring $revstring"
for checkno in $(echo $checkstring);
do
grep $checkno numbers
done
Note that this will get you duplicate output for lines containing more than one sequence, but just run that through |sort -u to eliminate them.
Upvotes: 0