Added support for -o flag: only print matching content

master
Aadhavan Srinivasan 1 month ago
parent f2b8812b05
commit dcd712dceb

@ -372,7 +372,10 @@ func thompson(re []postfixNode) *State {
func main() { func main() {
invertFlag := flag.Bool("v", false, "Invert match.") invertFlag := flag.Bool("v", false, "Invert match.")
//onlyFlag := flag.Bool("o", false, "Print only colored content.") // This flag has two 'modes':
// 1. Without '-v': Prints only matches. Prints a newline after every match.
// 2. With '-v': Substitutes all matches with empty string.
onlyFlag := flag.Bool("o", false, "Print only colored content.")
flag.Parse() flag.Parse()
// Process: // Process:
@ -419,10 +422,21 @@ func main() {
for i, c := range test_str { for i, c := range test_str {
if indicesToPrint.contains(i) { if indicesToPrint.contains(i) {
color.New(color.FgRed).Fprintf(out, "%c", c) color.New(color.FgRed).Fprintf(out, "%c", c)
// Newline after every match - only if -v is disabled.
if !(*invertFlag) {
for _, idx := range matchIndices {
if i+1 == idx.endIdx { // End index is one more than last index of match
fmt.Fprintf(out, "\n")
break
}
}
}
} else { } else {
if !(*onlyFlag) {
fmt.Fprintf(out, "%c", c) fmt.Fprintf(out, "%c", c)
} }
} }
}
err = out.Flush() err = out.Flush()
if err != nil { if err != nil {
panic(err) panic(err)

Loading…
Cancel
Save