1

I am trying to use awk to print any matches that match a pattern in a specific column of data ($4) in a file stored in variable $file_log. The match has also got to be partial and case insenstive. This is the file data.

Protocol    Packets    Bytes    SourceIP
TCP         120        1000     EXT_SERVER
TCP         33         230      EXT_SERVER
UDP         260        157      100012_SERVER
ICMP        340        89       100012_SERVER

So if a user was to provide the input of 'ex' in the following code, the output would display all lines with EXT_SERVER under the $4 column.

read -p 'Type the Source IP code you wish to search for: ' src_ip_choice

This is what I have so far however there is no output, even though there is definitely data that matches the pattern I enter...

read -p 'Type the Source IP code you wish to search for: ' src_ip_choice
if grep -i -q "$src_ip_choice" "$specified_log"; then
    awk -F',' '$4~/$src_ip_choice/' $specified_log
else
    echo "The Source IP code you entered cannot be found within $specified_log"

P.S. I understand the column $4 does not need to be specified as 'EX' only appears in $4 anyway. However, this is a requirement.

Any help would be greatly appreciated!

Nigel Wash
  • 107
  • 7
  • 1
    Please read [how-do-i-find-the-text-that-matches-a-pattern](https://stackoverflow.com/questions/65621325/how-do-i-find-the-text-that-matches-a-pattern) to understand the issue with your question and then replace the word "pattern" with both regexp-or-string and full-or-partial everywhere it appears in your question and include regexp metachars in the "pattern" to be matched so we can see how you want that handled (e.g. should `e.` in `src_ip_choice` match `ex` from `ext` and `er` from `server` in your data or not?) – Ed Morton May 05 '21 at 14:24

1 Answers1

1

You may use this awk for ignore case match in 4th column:

s='[Ee][Xx]' # or read from user

awk -v re="$s" 'tolower($4) ~ tolower(re)' file

TCP         120        1000     EXT_SERVER
TCP         33         230      EXT_SERVER

$4 is 4th column and /[Ee][Xx]/ matches ex or EX or Ex or eX in 4th column.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Hi @anubhava is there a way to awk search based on the pattern provided by the user stored in the 'src_ip_choice' variable – Nigel Wash May 05 '21 at 08:25
  • Thanks for your help @anubhava !! If I use a variable that contains user input instead of '[Ee][Xx]', how can I make this case insensitive? – Nigel Wash May 05 '21 at 08:37
  • Yes surely one can do: `awk -v re="$s" 'tolower($4) ~ tolower(re)' file` – anubhava May 05 '21 at 10:04
  • 2
    or with gawk `awk -v IGNORECASE=1 -v re="$s" '$4 ~ re' file`. I wonder if the OP **really** wants a regexp comparison though - we can't tell from "pattern"... – Ed Morton May 05 '21 at 14:21