Tutorial :sed/awk + count char until relevant char



Question:

Dear friends

I have the following:

   PARAM=1,2,3=,4,5,6,=,7#,8,9  

How to count by sed/awk the even "=" character between PARAM until "#" character

For example

 PARAM=1,2,3=,4,5,6,=,7#,8,9  

Then sed/awk should return 3

OR

 PARAM=1,2,3=,4=,5=,6,=,7#,=8,9  

Then sed/awk should return 5

THX

yael


Solution:1

you can use this one liner. No need to use split() as in the answer. Just use gsub(). It will return the count of the thing that is replaced. Also, set the field delimiter to "#", so you only need to deal with the first field.

$ echo "PARAM=1,2,3=,4,5,6,=,7#,8,9" | awk -F"#" '{print gsub("=","",$1)}'  3  $ echo "PARAM=1,2,3=,4=,5=,6,=,7#,=8,9" | awk -F"#" '{print gsub("=","",$1)}'  5  


Solution:2

Here is an awk script that finds the count using field separators/split. IT sets the field separator to the # symbol and then splits the first word (the stuff to the left of the first # on the = character. An odd approach possibly, but it is one method. Note that it assumes there are no = characters to the left of param. If that is a bad assumption, this will not work.

BEGIN{ FS="#" }  /PARAM.*#/{     n = split( $1, a, "=" );     printf( "Count = %d\n", n-1 );  }  

It can be done with one line as well:

[]$ export LINE=PARAM=1,2=3,4=5#=6  []$ echo $LINE | awk 'BEGIN{FS="#"}/PARAM.*#/{n=split($1,a,"="); print n-1;}'   3  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »