grep -E "a|d$$" filename
This is what I have but it does not works. Can I get some advice how I should approach it?
CodePudding user response:
|
is OR, not AND. So your command returns lines that either contain a
or end with d
(I assume $$
was a typo for $
). To match both conditions sequentially, just put one pattern after the other, don't use |
.
If the file is one word per line, use:
grep 'a.*d$' filename
If there are multiple words per line, and you're using GNU grep
, you can use:
grep -P 'a\w*d\b' filename
\w
matches word characters, and \b
matches a word boundary after the d
.
This will match the whole line containing the word. If you only want to return the word itself, use
grep -P -o '\b\w*a\w*d\b' filename
The -o
option means to only show the part of the line that matches the regexp
CodePudding user response:
Using awk:
awk '{for (i=0; i<=NF; i ) {if ($i~/a.*d$/) {print $i}}}'
Using GNU awk, or any awk that implements regex for the record separator (RS
):
awk -v RS='[[:space:]] ' '/a.*d$/'
Using GNU grep:
grep -Po '[^[:space:]]*a[^[:space:]]*d(?=[[:space:]]|$)'