I have input.txt
abcd
abcg
To select lines beginning with 'a' and ending with 'g' I write:
cat input.txt | awk '/^a/' | awk '/g$/{print $0}'
How can I combine the regular expressions ^a and g$ to be able to use only one instance of awk?
I have input.txt
abcd
abcg
To select lines beginning with 'a' and ending with 'g' I write:
cat input.txt | awk '/^a/' | awk '/g$/{print $0}'
How can I combine the regular expressions ^a and g$ to be able to use only one instance of awk?
Just use a single regex that matches both start and finish:
awk '/^a.*g$/' input.txt
Or, if you really want to use two, you can combine them with &&:
awk '/^a/ && /g$/' input.txt
No need for awk, just grep:
grep "^a.*g$" input.txt
To make the answer as generic as possible using awk, here is an alternate way to perform the desired action, where pattern string is passed as variable from the command line.
Demonstration test data is embedded in this example.
Using the script
#!/bin/sh
sSTRT="${1}"
sEND="${2}"
echo "John Wells
John Wayne
Robert Wayne" |
awk -v sTrt="^${sSTRT}" -v sEnd="${sEND}\$" ' $0 ~ sTrt && $0 ~ sEnd '
and executing the command
script "John" "Wayne"
the output is
John Wayne
with other lines ignored.
Special note: the "^" abd "$" must be passed literally as part of the awk variables.