Ubuntu: Bash for loop - how can I include blank newlines? (IFS) [closed]


Please note this is pseudocode, and I am not trying to count lines this way, this question is to figure out how to include completely blank newlines in a for loop.

cat file

word        word  

Since there are a total of 5 lines, x should equal 5 in the end.

IFS=$'\n'  x=0  for line in $(cat file) ; do  x=$(($x+1))  done    echo $x  

However, the blank newlines are not being counted, and x equals 2 instead of 5.

I thought the IFS=$'\n' would have made this work how I wanted. Can someone please explain how to make the blank newlines be "counted" in the for loop?


You can do this using read in a while loop instead of a for loop:

#!/bin/bash  while read line; do      ((x++))  done < file  echo $x  exit 0  
~$ cat file  word        word  ~$ bash script.sh  5  


You can't do this using the shell's field splitting.

Adjacent whitespace characters from IFS are parsed together, so you cannot use field splitting to distinguish between adjacent whitespace IFS characters. From the standard (Shell and Utilities, section 2.6.5):

Each occurrence in the input of an IFS character that is not IFS white space, along with any adjacent IFS white space, shall delimit a field, as described previously.

That's just how it is.

Since this is a hypothetical question, and you haven't said what it is exactly that you're doing, I won't suggest another way.


I think you will need to use while read line instead:

x=0  while read line ; do      x=$(($x+1))  done  

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