Skip to content
Advertisement

How to get consolidated count of delimiter occurrence

I have a requirement to fetch the count the occurrence of ‘|’ in each line of a file then match the count with given inputcount, needs to throw exception when the count is wrong.

Say if the inputcount=3 and the file has following content

s01|test|aaa|hh
S02|test|bbb
so3|test|ccc|oo

then exception should get thrown on executing the line 2 and it should exit the file.

Tried below Awk command to fetch the count for each lines, but I was not sure how to compare and throw the exception, when it not matches

awk ' {print (split($0,a,"|")-1) }' test.dat

Can anyone please help me with it?

Advertisement

Answer

You may use this awk:

awk -v inputcount=3 -F '\|' 'NF && NF != inputcount+1 {exit 1}' file &&
 echo "good" || echo "bad"

Details:

  • -F '\|' sets | as input field separator
  • NF != inputcount+1 will return true if any line doesn’t have inputcount pipe delimiters.
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement