If you directly use strings under a
for loop, it will work per-word, not per-character. You need to use a
while loop with
read in order to parse letter-by-letter. Or introduce a numerical parameter that would iterate over the string.
In addition, when using
read, you need to make sure that newlines and whitespaces arent interpreted as delimiters and force
read to read one char at a time.
Here's a working version:
test="this is a
echo -n "$test" | while IFS= read -N 1 a; do
if [[ "$a" == $'\n' ]] ; then
echo "FOUND NEWLINE"
You could replace
$'\x0a', since they all represent the same newline code. But it is not the same as
\r - this stands for carriage return (return to the beginning of line). On Linux systems, newlines are represented using
\n, but on Windows for example, they are represented by a sequence of
\r\n instead. That is why if you had a text file from Windows, you could detect newlines also by searching for