Skip to content

Commit 323c476

Browse files
committed
grep -Ec plus tr
1 parent 38460b8 commit 323c476

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

book.org

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1323,6 +1323,39 @@
13231323
\0 problem. But then you need to explain the awk model to your
13241324
coworker.
13251325

1326+
*** grep -Ec
1327+
Say you want to find lines that match 2 words, not just 1. in whatever order.
1328+
1329+
#+begin_src bash
1330+
echo "foo bar" | grep foo | grep bar # That works, but it only works for very fixed inputs.
1331+
1332+
echo "foo bar" | grep -E 'foo.*bar' # That doesn't , because order matters.
1333+
1334+
echo "foo baz" | grep -E '(foo|bar)' | grep -E '(foo|bar)' # That is not going to work either, because if only one word matches, it will match twice.
1335+
#+end_src
1336+
1337+
Here's how we can match multiple things from a list.
1338+
=echo "foo bar" | tr ' ' '\n' |grep -Ec "(foo|bar)"=
1339+
1340+
#+begin_src bash
1341+
1342+
match_two () {
1343+
while read line; do
1344+
if [ "$(tr ' ' '\n' <<<"$line" | rg -Uc "^($search)$")" = 2 ]; then
1345+
echo "$line"
1346+
fi
1347+
done
1348+
}
1349+
1350+
cat file_with_two_words_per_line.txt | match_two "foo|bar|baz"
1351+
#+end_src
1352+
1353+
With this, you can find out how many matches happened in that
1354+
line. The example above filters lines which have 2 words from the
1355+
'foo|bar|baz' regex.
1356+
1357+
1358+
13261359
*** Set operations
13271360
There are lots of other "set level" operations you can perform on
13281361
files/streams using basic unix tools.

0 commit comments

Comments
 (0)