using tail -f and tr in a script

I have file that is being constantly written to

example: file.txt
ABC
EBC
ZZZ
ABC

I am trying to create a simple script that will tail this file and at the same time using tr to change B to F on lines containing 'B'.

I tried this and it doesn't seem to work.

#!/bin/bash
tail -f file.txt | grep 'C' | tr 'B' F'

the output should be like this:

AFC
EFC
AFC

Can anyone tell me what I'm doing wrong? I am not trying to change the letters in the file itself, but only the output being shown on screen.

I think all you need to do is

tail -f file | tr B F

to get what you want.

Sorry I actually made a mistake in my original post. The output should only show the lines that contain 'C' also.

by just running tail -f file | tr B F will putput the ZZZ lines as well.

If by "also" you mean "B" and "C":

tail -f file.txt | egrep 'B|C' | tr 'B' 'F'

Note: The quotes in the tr statement are important or you can get very strange results.

# grep C file | tr B F
AFC
EFC
AFC

I tried the above, but if I do

echo ABC >> file.txt

it is not showing any live output, ABC is being written to file.txt, but the tail -f does not seem to work with tr.

maybe because of tail -f opens a file on fs so it is trigger for process to the block buffering and (after the pipe |) coming second command ( tail -f file | grep C | tr B F ) so in this "tr" comm does not access to data block in buffer but may be use if avalaible option related buffer opt )

 
# tail -f infile | grep --line-buffered "C" | tr 'B' 'F'

Regards
�ygemici�

Interesting puzzle.

These two work:
tail -f file.txt | tr 'B' 'F'
tail -f file.txt | egrep 'B|C'
This one doesn't
tail -f file.txt | egrep 'B|C' | tr 'B' 'F'

I wonder if tail is closing and opening the pipe for each iteration?

The process (egrep) in the middle is the problem. This works:

tail -f file.txt | awk '/B|C/{print;fflush()}' | tr 'B' 'F'
1 Like