0

So, I have a data file and I would like a match to occur only if a match is found between the 2nd and third Vertical Bars (|)

So given this data sample, I if I search for 'wilson' I want the 2nd line to return, but not the 3rd and 5th lines which also contain the term 'wilson'.

The data sample:

| 2015-08-21 - 10:15 | jones | view | Main.Home | | 172.29.192.106 | | 2015-08-21 - 10:31 | wilson | view | Main.Home | | 172.19.6.107 | | 2015-08-21 - 11:40 | smith | resetpasswd | wilson | Mozilla | 172.19.15.105 | | 2015-08-21 - 11:41 | james | view | Main.ChangePassword | | 172.19.15.102 | | 2015-08-21 - 11:41 | james | changepasswd | wilson | | 172.19.15.102 | | 2015-08-21 - 11:41 | james | view | Main.Home | | 172.19.15.102 | | 2015-08-22 - 08:31 | doe | view | Main.Info | | 172.19.6.103 | 

2 Answers 2

3

For your sample input:

$ cat /tmp/data | 2015-08-21 - 10:15 | jones | view | Main.Home | | 172.29.192.106 | | 2015-08-21 - 10:31 | wilson | view | Main.Home | | 172.19.6.107 | | 2015-08-21 - 11:40 | smith | resetpasswd | wilson | Mozilla | 172.19.15.105 | | 2015-08-21 - 11:41 | james | view | Main.ChangePassword | | 172.19.15.102 | | 2015-08-21 - 11:41 | james | changepasswd | wilson | | 172.19.15.102 | | 2015-08-21 - 11:41 | james | view | Main.Home | | 172.19.15.102 | | 2015-08-22 - 08:31 | doe | view | Main.Info | | 172.19.6.103 | 

You can use awk:

$ awk '-F|' 'BEGIN { OFS = "|" }{ if ($3 ~ "wilson") { print } }' /tmp/data | 2015-08-21 - 10:31 | wilson | view | Main.Home | | 172.19.6.107 | 

Instead of $3 ~ "wilson" you could also use $3 == " wilson " assuming that there will always be spaces surrounding the field.

To answer your follow-up question, you could wrap it in a Bash script:

$ cat foo.sh #/bin/bash names="$(cat patlist.txt)" for name in ${names}; do awk -F'|' '$3 == " '"${name}"' "' /tmp/data done $ cat patlist.txt wilson jones $ bash foo.sh | 2015-08-21 - 10:31 | wilson | view | Main.Home | | 172.19.6.107 | | 2015-08-21 - 10:15 | jones | view | Main.Home | | 172.29.192.106 | 
3
  • 3
    +1 a bit more terse awk -F'|' '$3 == " wilson "' FILE Commented Aug 26, 2015 at 18:27
  • This works well, however, if I wanted to replace "wilson" with a list of user names say in patlist.txt, how I could I use awk this way? Commented Aug 26, 2015 at 18:45
  • @OffTheGold Replace each wilson with a different (individual) name or all of them with the same? Commented Aug 26, 2015 at 19:51
0

Easiest would be to tie the regex to some other field, e.g. :[0-9][0-9] | wilson, though this risks false positives. More complicated would be instead to use awk and split the data into columns, then apply the regex in awk against only the second column.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.