tail, grep and cut

Hello all,

I have some weird problem that kinda baffles me. Say I have the following test file:

claudia:~/tmp$ cat testfile.txt
This is a test line
This is the second test line
And yeah, this is the third test line

Then say I want to tail the file, grep for the word "third" then display only the 7th field. I would do some like this:

claudia:~/tmp$ tail -f testfile.txt | grep third | cut -d\  -f7

However, that does not work. I get no error, but no output either. If I leave out the "cut" part, then the grep works fine:

claudia:~/tmp$ tail -f testfile.txt | grep third
And yeah, this is the third test line

If I do the same with "cat" then it works fine, the expected output appears:

claudia:~/tmp$ cat testfile.txt | grep third | cut -d\  -f7
test

What am I doing wrong ?

Thanks,
Sylaan

What are you trying to accomplish with the tail -f command?
And then your grep "third"?

Are you simply trying to narrow your search to the last ten lines (default of the tail command), and then find the line with the word "third"? If so, try without the -f on the tail command.

By the way, I am not convinced that your example works fine when you think it does. The -f on the tail command would appear to keep the process running awaiting additional input.

It was just an example to illustrate a real-world problem that I have.

Basically I need to tail a syslog file, grep for a certain pattern then display a certain field from the matched line. What I wanted to say with my example is that the "cut" after the "grep" is not producing anything, even though it should (as far as I can tell). It does not matter if I tail a syslog file or a testfile created by me, it should still work.

And sure, tail -f waits for more input but that does not matter, by default it should still list the last 10 lines or so from the file, which is plenty of input for my grep and cut.

--
Sylaan

i will let others explain to you. in the meantime, you can try this out

# tail -f file | awk '/third/{print $7}'

Nice, that works fine :slight_smile: Thanks. One more quick question: how would I print everything from the 7th field to the end of the line , in awk ? Something like cut's -f 7- .

Trying this out on several files, because the -f keeps the process open, appears to therefore not allow any additional commands after the first pipe.
tail -f file | grep val1 >will work
tail -f file | grep val1 | grep val2 >will not work

but,
tail file | grep val1 | grep val2 > will work

normally you use a for loop

tail -f file | awk '/third/{ for(i=7;i<=NF;i++) print $i }'

Thanks guys, I understand now why I can't have 2 pipes after a tail -f.

You are right, the loop shoud do the trick. However, that "print $i" prints each word on a new line. So I tried this and it worked better:

tail -f /var/log/syslog | awk '/10.10.[02]/{ for(i=4;i<=NF;i++) printf  "%s ",$i; printf "\n" }'