1

I need to write a shell script to read a text file in and perform operations on it to count all distinct words in the text file.

I have all of the commands needed to do these operations, but how would I go about inputting the text file into the shell script to then use through the commands?

so a command that I use is this, how would i go about having the text.txt as a variable so that I can just call the variable in the script?

tr '[A-Z]' '[a-z]' < text.txt
0

You can use simple command substitution:

variable=`cat text.txt`
echo $variable

Or in bash:

variable=$(cat text.txt)

Same with:

variable=`tr '[A-Z]' '[a-z]' < text.txt`
1

Tools like tr and wc can operate on files; you don't have to pass strings to their stdin. To answer your question:

how would I go about having the text.txt as a variable so that I can just call the variable in the script?

The syntax for that is:

input=text.txt # or other file name
tr '[A-Z]' '[a-z]' $input
0

Example file

foo
        bar
    foo bar
foobar f0o b@rred

Generated via

echo -e 'foo\n\t\tbar\n    foo bar\nfoobar f0o b@arred' | tee -a /tmp/foo.bar

File continence in bash variable (short-hand for $(cat file))

v="$(</tmp/foo.bar)"

Use variable as input (stripped of non-printable characters) for another command

sed 's#@#a#; s@0@o@' <<<"${v//[![[:print:]]]}" | tail -1

Should output the last line, replacing @ with a and 0 with o

foobar foo barred

Also one my wish to look into mkfifo... best of luck with text.txt parsing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.