Usando awk
:
Salve o seguinte código em um arquivo de texto e torne-o executável ( chmod u+x filename
).
Em seguida, execute-o assim:
awk -f filename inputfile
Isso é imenso comparado às soluções em perl
ou python
, estou adicionando isso apenas porque awk
ou sed
foi a solução preferida e para mostrar que é possível usar awk
, embora seja não é conveniente.
{
#list of words to look for in parentheses: (named "w" to speed up adding items)
w[0] = "bar";
w[1] = "blat";
#"bool" value whether of not to crop spaces around omitted parenthesis with their content
cropSpaces = 1;
spaces = 0; #space counter used for cropping
open = 0; #open/nested parenthesis counter
st = 0; #marks index where parenthesis starts
end = 0; #marks index where parenthesis ends
out = 0; #"bool" value indicating whether or not the word has been found
for(i = 1;i-1 < length($0);i++){ #for each character
c = substr($0,i,1); #get character
if(c == "("){ #character is '('
open++; #increment parenthesis counter
if(open == 1) st = i+1; #marks start of parenthesis (if not nested)
}
else if(c == ")"){ #char is ')'
open--; #decrement parenthesis counter
if(open == 0) end = i; #mark end of parenthesis (if not nested)
}
else{ #any other char
if(open == 0){ #outside of parenthesis
if(cropSpaces && c == " "){ #char is space (and cropSpaces option is not 0)
if(spaces == 0) printf c; #print space if not sequential
spaces++; #increment space counter
}
else{ #any other char
spaces = 0; #set previous spaces counter to 0
printf c; #print char
}
}
else if(!out){ #inside of parenthesis (and no word has been found)
for(j = 0; j < length(w); j++){ #for every word in list
if( substr( $0,i,length(w[j]) ) == w[j]){ #if word matches
out = 1; #word has been found
break; #do not look for any other words
}
}
}
}
if(open == 0 && out){ #outside of parenthesis and word found in previous parenthesis
printf substr($0,st,end-st); #print content
out = 0; #reset "word found" indicator
spaces = 0; #reset spaces counter
}
}
printf "\n"; #print newline
}