0

I'm currently trying to make a bash script with the ability to read a file character by character, I searched the forums and came across this line of code

while read -n1 c; do
  echo $c
done < $1

While it gets the job done, it doesn't include whitespaces, can someone help me?

decipher
  • 1
  • 3
  • 1
    I don't see the problem. Inspect https://ideone.com/Aiuic8 -- running your original code -- there's a blank line on output where a space came in on input. (Granted, `echo` isn't printing a space on that blank line, but that's because you're using `echo $c` instead of `echo "$c"`, nothing about the `while read`). – Charles Duffy Aug 26 '22 at 16:43

1 Answers1

0

The default input field seperator (IFS) is one of space, tab or newline; because the space is processed as a separator you see it 'disappear' in your reads (ie, c is left empty).

One option for 'keeping' the space is to redeine IFS as a blank, eg:

while IFS='' read -n1 c; do
  echo "$c"
done < $1

NOTE: wrap the variable reference in double quotes to disable globbing (eg, echo * gets expanded to a list of all files in the current directory; echo "*" prints an actual *)

markp-fuso
  • 28,790
  • 4
  • 16
  • 36
  • 1
    It's a different problem than the one the OP asked about, but `echo "$c"` or a `*` will be replaced with a list of filenames. – Charles Duffy Aug 26 '22 at 16:41
  • That said, I don't see this changing anything. Observe https://ideone.com/Aiuic8 running the OP's original code; spaces are still being looped over, even without `IFS=''`. – Charles Duffy Aug 26 '22 at 16:44
  • replace `echo "$c"` with `echo ":$c:"`; without `IFS=''` spaces show up as `::` (nothing between colons), with `IFS=''` the spaces show up as `: :` (space between the colons) – markp-fuso Aug 26 '22 at 16:46
  • 1
    Heh. Good point. Visually identical output, but it's not actually the same. I'll adjust the duplicate list to add one that covers that. – Charles Duffy Aug 26 '22 at 16:47