tags:

views:

29

answers:

2

hi all

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

A: 

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
Mark Wilkins
it possible to write this in one lineBecause I need to run the awk in bash scriptyael
yael
for example echo $LINE | awk ........(in LINE I have the (PARAM=1,2,3=,4=,5=,6,=,7#,=8,9)yael
yael
@yael, I added a one-line example.
Mark Wilkins
OK thanxthe second quastion if I not have the "#" char , then how to change the awk syntax to count the "=" char ,the target is to support the two cases (1) case if I hace "#" , and the second case if I dont have the "#" char
yael
/PARAM.*#/ --> how to change it to support until end of line or until "#" charyael
yael
I'm a bit unsure of what you are asking. The /PARAM.*#/ just specifies what lines the code block applies to.
Mark Wilkins
but if export LINE=PARAM=1,2=3,4=5=6 , then awk not print any countmy target to change the awk to print the count also if "#" not defined in the LINEyael
yael
I see what you are asking. You could change it simply to /PARAM/. Or even just remove it and use awk 'BEGIN{FS=#"}{n=split...}
Mark Wilkins
OK great -:)yael
yael
+1  A: 

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
ghostdog74
That will fail if there's an equal sign before or within "PARAM" (the OP specified 'between PARAM until "#" character'. I'm not sure what is meant by "even" in 'the even "=" character'.
Dennis Williamson