Home > Enterprise >  Detect double new lines with bash script
Detect double new lines with bash script

Time:02-04

I am attempting to return the line number of lines that have a break. An input example:

2938
383

3938
3

383
33333

But my script is not working and I can't see why. My script:

input="./input.txt"
declare -i count=0

while IFS= read -r line;
do
    ((count  ))
    if [ "$line" == $'\n\n' ]; then
        echo "$count"
    fi
done < "$input"

So I would expect, 3, 6 as output.

I just receive a blank response in the terminal when I execute. So there isn't a syntax error, something else is wrong with the approach I am taking. Bit stumped and grateful for any pointers..

Also "just use awk" doesn't help me. I need this structure for additional conditions (this is just a preliminary test) and I don't know awk syntax.

CodePudding user response:

The issue is that "$line" == $'\n\n' won't match a newline as it won't be there after consuming an empty line from the input, instead you can match an empty line with regex pattern ^$:

if [[ "$line" =~ ^$ ]]; then

Now it should work.


It's also match easier with awk command:

$ awk '$0 == ""{ print NR }' test.txt
3
6

CodePudding user response:

You can also just use GNU awk:

gawk -v RS= -F '\n' '{ print (i  = NF); i  = length(RT) - 1 }' input.txt
  •  Tags:  
  • bash
  • Related