Reading from file
Hello! I want to read text from a file (the file is just a normal paragraph) word by word. To be honest I have no clue how to do this. I can't use input redirection, I need to read from a file given by parameter 1.
Here's the summary of the problem: I need to read from a file ($1) word by word (after which I apply a test to each word but I think I can do that). How can I do this? Can I use the read statement? |
read file where:
- BASH (shell) ? - PHP ? - Perl ? ... be descriptive and you will get answers, describe the system you use (RHEL, Deb...) and what language you want to use (Perl, Python, PHP....) |
I'm guessing you want instructions for the shell because you mention input redirection and $1. Just guessing though.
I believe the traditional method is to use a read command enclosed within a while loop, with the input of the entire loop redirected from the file. So ... why can't you use input redirection? |
I can't use input redirection because this is an assignment for a class. The program can only be invoked by the program name and its argument. This is a bash script with the text file in the same directory as the script, on a Ubuntu system.
If I can't figure anything else out I'll use input redirection but I will lose points for doing so. |
say I have a loop like this:
Code:
while read word Code:
while read word < $1 |
Quote:
|
If you can't use redirections*, have a look at file descriptors.
To work word-by-word, try using an array. (hint: take a look at read's options) *I get the sense that this rule only applies to launching the script itself, but it would be very strange indeed if it also referred the commands inside the script. You might want to get clarification on that. |
To read word by word, in alternative to arrays, you can try the tr command to change space/tabs with newlines (so that you have a single word on each line) and feed the loop with the result.
|
When I want to read a file a word at a time I use for to iterate over the output of cat. Don't know if that's the most efficient way to do it, but it works and it's very simple.
Since you say it's an assignment and I've already found some alternatives to my usual method in less than 60 seconds via Google (all of which are a lot more complicated than mine and I'm not seeing how they're technically better), I'm a bit reluctant to give you actual code but if you look at the for and cat commands and also command substitution it should be easy to figure out. |
I ended up solving the problem using the sed command inside a do loop.
Telengard: it causes a runtime error, something about the syntax being wrong. David: yes I could use redirections in the script, just not when invoking it. sorry for the confusion. to get this to work however, I didn't need them. |
All times are GMT -5. The time now is 12:53 AM. |