Linux – one line command to print the longest line within the files in a directory

filesgreplinux

Lets assume that I am in a directory with a lot of files.
How would you search the contents of all the files in a directory and display the longest line that contains the string “ER” but not “Cheese”?

So far, to my best knowledge, I'm trying to do this in one line command.

I am thinking I need to use grep -r for recursive, in order to search through all the files in the directory
but my end goal is to just display the longest line, so I assume so far it should be like:

grep -r -e "ER" 

and when I do -v "Cheese" attached to it out of small hope, it doesn't work of course.

Is this not possible with one line of command? If so, what would I need to do in multiple lines?

Best Answer

Here's an awk solution:

 awk '/ER/ && !/Cheese/ {if (length($0) > maxlen) { maxline=$0; maxlen=length($0);}} END {print maxlen, maxline;}' *

(it also prints the length of the longest line, but if you don't want that, just say ... END {print maxline;}.

The advantage over the grep solution of Jeremy Dover is that it does one pass over the input. The disadvantage is that if there are multiple lines with the same max length, it only prints the first one (or the last one if you use >= to compare the lengths); the grep solution prints all of them.

Related Question