Nitheesh MN
Nitheesh MN

Reputation: 628

How to print the longest word in a file by using combination of grep and wc

iam trining to find the longest word in a text file. i tried it and find out the no of characters in the longest word in a file by using the command

wc -L

i need to print the longest word By using this number and grep command .

Upvotes: 0

Views: 1696

Answers (1)

chepner
chepner

Reputation: 531858

If you must use the two commands give, I'd suggest:

grep -E ".{$(wc -L < test.txt)}" test.txt

The command substitution is used to build the correct brace expression to match the line(s) with exactly the given number of characters. -E is needed to enable extended regular expression support; otherwise, the braces need to be escaped: grep ".\{...\}" test.txt.

Using an awk command that makes a single pass through the file may be faster.

Upvotes: 3

Related Questions