im trying to remove all lines that have any 3 characters in alphabetical order with sed is there an easy way to do this instead of a bunch of pattern lines
sed -i '/abc/d
/bcd/d
....
/xyz/d' file.txt
im trying to remove all lines that have any 3 characters in alphabetical order with sed is there an easy way to do this instead of a bunch of pattern lines
sed -i '/abc/d
/bcd/d
....
/xyz/d' file.txt
With your attempted code, please try following awk code, where we are not writing all combinations of continuous alphabets. IMHO awk will be much efficient then sed here.
awk '
BEGIN{
FS=""
num=split("a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z",arr1,",")
for(i=1;i<=num;i++){ letters[arr1[i]]=i }
}
{
for(i=1;i<=NF;i++){
if(($i in letters) && ($(i+1) in letters) && ($(i+2) in letters)\
&& (letters[$i]+1==letters[$(i+1)]) && (letters[$i]+2==letters[$(i+2)])\
&& (letters[$(i+1)]+1==letters[$(i+2)])){
print $i $(i+1) $(i+2)
}
}
}
' Input_file
Explanation: Simple and detailed explanation for whole awk program would be:
Explanation of BEGIN block of awk program:
FS) as NULL for all lines in awk so that each character could be compared to find out 3 consecutive occurrences of letters.split function of awk creating an array named arr1 where splitting all alphabets(small letters) into it with delimiter of , here.for loop till value of num(could be written as 26 also since number of alphabets are always fixed), where creating an array named letters which has index as alphabets and its value will be their place value(their number on which they occur, eg: for a it will be 1).Explanation of main block of awk program:
Running a for loop from 1st field to till NF all fields of current line basically.
Then checking conditions there(basically checking if current field and next 2 fields are coming in letters array or not AND checking if their sequence is continuous or not).
If all conditions mentioned are met then printing current and next 2 fields(which will basically print 3 letters).
This might work for you (GNU sed):
sed -En '1{x;s/^/abcdefghijklmnopqrstuvwxyz/;x};G;/(...).*\n.*\1/!P' file
On the first line, introduce a literal alphabet in the hold space.
On each line, append the alphabet and using a three character back reference, compare it the the alphabet.
If there is a match, delete the line, otherwise, print the first line only.
N.B. The use of the -n turns off implicit printing and thus only when a match fails is the line printed.