0

I wrote a shell script that uses cat and tr commands to generate a file. My shell script looks like

#!/bin/bash
printf "generating random file > plaintext \n"
cat -v | tr "a-z" "b-y" < plaintext  > generatedtext 

On executing the script, it doesn't terminate the cat command and when I've CTRL + Z to stop the shell script execution. Now, when I look into the contents of the generatedtext - the first character is altered(based on tr) and the rest of the characters are all one and the same as in the plaintext.

For example, if the contents of plaintext

This is an apple.

After shell execution, the contents of generatedtext

xhis is an apple.

  • 2
    If you don't have any control chars then cat is useless.. – heemayl Apr 12 '15 at 17:59
  • 1
    Your tr ranges are dissimilar: a-z is 26 characters, b-y is 24. Is that intentional? (Your input text characters x, y, and z will all end up as y.) – roaima Apr 12 '15 at 20:25
  • @roaima yes it was intentional. – GIRI Apr 12 '15 at 20:35
1

You need the tr after you read the plaintext file:

#!/bin/bash
printf "generating random file > plaintext \n"
cat -v < plaintext | tr "a-z" "b-y" > generatedtext

In your question plaintext is redirected to tr not cat. Alternatively, you can run the piped commands in a subshell:

#!/bin/bash
printf "generating random file > plaintext \n"
( cat -v | tr "a-z" "b-y" ) < plaintext  > generatedtext 
  • it worked when I executed as a shell command. But when I placed it in a shell script(inside the program.sh file) it just replaces the first character – GIRI Apr 12 '15 at 17:48
  • @GIRI which version of bash are you using? which OS? It works for me when invoked within a shell script. Does the script not exit until you press CTRL+Z ? – rahul Apr 12 '15 at 17:54
  • @GIRI, just realized, by any chance do you have the case mixed up ? tr "A-Z" "B-Y" ? That could explain why only the first letter is replaced. – rahul Apr 12 '15 at 17:56
  • I'm on OS X, script exits without ctrl+Z(tr after plaintext). bash version is 3.2.57 – GIRI Apr 12 '15 at 17:57
  • ya that i was the issue. case mixed up my input file has the uppercase start character. – GIRI Apr 12 '15 at 18:16

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.