I am having trouble figuring out where to place the \ in this command.
grep "^D.*\(A1|A2|A3\)$" input.txt > output.txt
I'm searching for each line that starts with a D and ends with A1, A2, or A3, which is at the end of the line.
I am having trouble figuring out where to place the \ in this command.
grep "^D.*\(A1|A2|A3\)$" input.txt > output.txt
I'm searching for each line that starts with a D and ends with A1, A2, or A3, which is at the end of the line.
You need to escape the pipes (|).
$ grep "^D.*\(A1\|A2\|A3\)$" <(printf 'D%s\n' A1 A2 A3)
DA1
DA2
DA3
Or use option -E for extended regex, then you don't need to escape anything.
$ grep -E "^D.*(A1|A2|A3)$" <(printf 'D%s\n' A1 A2 A3)
DA1
DA2
DA3
You just needed to escape the or bars - you were almost there:
grep "^D.*\(A1\|A2\|A3\)$"
Note you can also use egrep instead of all the escapes:
egrep "^D.*(A1|A2|A3)$"
Here is sed implementation, that uses the combination of the option -n and the command p:
sed -rn '/^D.*(A1|A2|A3)$/p' in-file
sed -n '/^D.*\(A1\|A2\|A3\)$/p' in-file
sed -n '/^D.*A[1-3]$/p' in-file
option -r, --regexp-extended: use extended regular expressions in the script.
option -n, --quiet, --silent: suppress automatic printing of pattern space.
command p: print the current pattern space.