0

I have a file which has some stats and counters stored for some ACL rules. I want to design a shell script to read that file and parse those counters.

I have done the similar thing in c programming language where I have opened and stored the content of the file in some buffer and with sscanf, I have parsed the output of the file

Below is the content of files

vlan_id: 0
HITS    ACL rules:
0   0: allow icmp src 1.1.1.1 dst 1.1.0.0 mask 255.255.0.0,
0   1: deny icmp dst 6.8.9.1,
0   2: deny icmp src 3.2.2.1,
0   3: deny tcp src port 3210,
0   4: deny tcp src 6.0.9.9,
0   5: deny udp src port 432,
0   6: deny udp src 43.43.43.1,
0   7: deny tcp src port 435,
0   8: deny udp dst port 554,
22  9: deny all,
the number of passed packets: 0
the number of dropped packets: 22

In c programming language, I have wrote the below code to parse it

   //Read atmost 127 characters or till it encounter comma(,).
   num = sscanf(line, "%d %d: %127[^,\n]",&hits,&n,&rule[0]);
   if (num ==  3)
   {
       g_list_of_rules[i].hits = hits;
       strncpy_s(g_list_of_rules[i].rule,
                 ACL_MAX_STR_LEN, rule,
                 ACL_MAX_STR_LEN-1);
       i++;

   }

Similar thing I want to accomplish in the shell script.

I mean this sscanf functionality ( sscanf(line, "%d %d: %127[^,\n]",&hits,&n,&rule[0]); ) where I am parsing and storing three values in three different variables. So similar kind of functionality I am looking in shell script or in any other linux utility like sed or grep

For example, for the below rule,

0 0: allow icmp src 1.1.1.1 dst 1.1.0.0 mask 255.255.0.0,

all three values I want in separate variables. So if I do echo $n1, $n2, $str then n1 should print 0, n2 should print 0 and n3 should print allow icmp src 1.1.1.1 dst 1.1.0.0 mask 255.255.0.0

if someone has idea or thoughts, please share it.

1 Answer 1

0

You can try this with awk

awk -F': ' -v OFS="," '{split($1,a," "); split($2,b,","); print a[1],a[2],b[1]}' input_file

This will put in variable a[1] the first zero, in a[2] the second zero and in b[1] the rest of the line (w/o comma)

2
  • Thank you for response. I have a question, how to display it in console?. When I execute the above command it does not print anything
    – vivek
    May 10 at 11:45
  • @vivek, will edit my answer and give you example output you can modify depend of your requirements. May 10 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.