Bash scripting: parsing a text file character-by-character
Hi all,
Is there a way to process individual characters one-by-one from a text file in Bash, or is that hoping for a little too much from this lovable old clunker? Thanks, cc |
Not the exact solution of your problem but might take you to the right path
Code:
sed 's/\(.\)/\1\n/g' <file> |
Code:
~$ help read |
Quote:
|
Quote:
Well I'm simply more realistic about Bash's capabilities now I know how it arose and what for. This task is something I could jot down on the back of a fag packet in C, but that was very many years ago and I can't recall the relevant functions. ISTR C has a getchar() function which does this. I need a Bash equivalent that I can run in an 'until' loop until the next character read from the file is EOF. It's annoying that so much I want to do in Linux is usually something I've yet to learn! |
Code:
while read -n 1 ; do |
Quote:
Solutions already posted show how to do what you want in bash; if you want to do a non-blocking read -- simple in C -- then things get a little more "interesting" :) ISTR that getchar() and putchar() are actually C #define macros that hide an underlying buffer for convenience and performance but that also comes from "very many years ago" so take it with a pinch of salt. |
Quote:
|
Okay, well we're off and running, but a few teething problems. This is the relevant code fragment as it stands after some tinkering:
Code:
#!/bin/bash How do I tell 'read' to just fetch one character each time, but every iteration make it take the *next* character and so on in sequence until the end of the file is reached? Thanks, guys. cc |
Quote:
Code:
awk 'BEGIN{FS=""}{ |
Quote:
Kevin Barry |
Code:
#!/bin/bash |
Excellent work, Gnashley! Works like a charm. :D
|
In case you're interested in why Gnashley's solution works ...
textfile.txt is opened only once, by the indirection operator < on the while; do; <commands>; done compound command. I guess you were thinking it was the read command that opened textfile.txt when you coded while read -n$x char |
All times are GMT -5. The time now is 05:11 AM. |