I have a file named users.txt
that contain a list of users in this format:
bob
john
alex
tom
I need to run this AWK statement and use each of those names as patterns and output to a file
awk '/PATTERN/{x=NR+6}(NR<=x){print}' input.txt >> output.txt
How do I make AWK loop through each name and use them as search patterns?
Example input file:
bob@servername
10/09/2018 19:11:19
50152 command issued.
weid: A1Pz64385236
job_name: xxx-xxx-xxx-xxx-xxx-xxx
command: fff-fff-fff-fff-
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
alex@servername
10/09/2018 16:33:55
50152 command issued.
weid: A1Pz64385236
job_name: xxx-xxx-xxx-xxx-xxx-xxx
command: fff-fff-fff-fff-
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
doug@servername
10/09/2018 13:22:66
50152 command issued.
weid: A1Pz64385236
job_name: xxx-xxx-xxx-xxx-xxx-xxx
command: fff-fff-fff-fff-
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::`
Output should be like this, only with users which are in the users.txt file (there are a lot more users in the input file which I don't want to see)
bob@servername
10/09/2018 19:11:19
50152 command issued.
weid: A1Pz64385236
job_name: xxx-xxx-xxx-xxx-xxx-xxx
command: fff-fff-fff-fff
While reading the first file, append each line to a pattern string, separating them with |
. Then when processing the second file test the line against the pattern.
awk 'NR==FNR { pattern = pattern (pattern ? "|" : "") $0; next }
$0 ~ pattern { x = FNR + 6 }
FNR <= x' users.txt input.txt
I tested this on Mac OS High Sierra and Debian Linux with your sample files, the result was:
bob@servername
10/09/2018 19:11:19
50152 command issued.
weid: A1Pz64385236
job_name: xxx-xxx-xxx-xxx-xxx-xxx
command: fff-fff-fff-fff-
alex@servername
10/09/2018 16:33:55
50152 command issued.
weid: A1Pz64385236
job_name: xxx-xxx-xxx-xxx-xxx-xxx
command: fff-fff-fff-fff-
You can probably use grep too:
grep input -wf users -A 6
This will match the names from the users file to the input file and print 6 lines following the match. With the w
flag grep will only match complete words, you can leave it out depending on your needs.
If your grep does not support -A
, this may work:
grep input -wf users -n | cut -d: -f1 | xargs -n 1 -I {} sed -n "{},/^::*$/ p" input
or this:
grep input -wf users | xargs -n 1 -I {} sed -n "/{}/,/^::*$/ p" input
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.