user3546411
user3546411

Reputation: 651

How to read a space in bash - read will not

Many people have shown how to keep spaces when reading a line in bash. But I have a character based algorithm which need to process each end every character separately - spaces included. Unfortunately I am unable to get bash read to read a single space character from input.

while read -r -n 1 c; do printf "[%c]" "$c" done <<< "mark spitz" printf "[ ]\n"

yields

[m][a][r][k][][s][p][i][t][z][][ ]

I've hacked my way around this, but it would be nice to figure out how to read a single any single character. Yep, tried setting IFS, etc.

Upvotes: 3

Views: 1774

Answers (1)

paxdiablo
paxdiablo

Reputation: 881113

Just set the input field separator(a) so that it doesn't treat space (or any character) as a delimiter, that works just fine:

printf 'mark spitz' | while IFS="" read -r -n 1 c; do
    printf "[%c]" "$c"
done
echo

That gives you:

[m][a][r][k][ ][s][p][i][t][z]

You'll notice I've also slightly changed how you're getting the input there, <<< appears to provide a extraneous character at the end and, while it's not important to the input method itself, I though it best to change that to avoid any confusion.


(a) Yes, I'm aware that you said you've tried setting IFS but, since you didn't actually show how you'd tried this, and it appears to work fine the way I do it, I have to assume you may have just done something wrong.

Upvotes: 3

Related Questions