Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

max comma's on one line, using bash script

I have some \n ended text:

She walks, in beauty, like the night
Of cloudless climes, and starry skies
And all that's best, of dark and bright
Meet in her aspect, and her eyes

And I want to find which line has the max number of , and print that line too. For example, the text above should result as

She walks, in beauty, like the night

Since it has 2 (max among all line) comma's.

I have tried:

cat p.txt | grep ','

but do not know where to go now.

like image 563
digit plumber Avatar asked May 23 '26 04:05

digit plumber


2 Answers

You could use awk:

awk -F, -vmax=0 ' NF > max { max_line = $0; max = NF; } END { print max_line; }' < poem.txt

Note that if the max is not unique this picks the first one with the max count.

like image 191
FatalError Avatar answered May 25 '26 18:05

FatalError


try this

awk '-F,' '{if (NF > maxFlds) {maxFlds=NF; maxRec=$0}} ; END {print maxRec}' poem

Output

She walks, in beauty, like the night

Awk works with 'Fields', the -F says use ',' to separate the fields. (The default for F is adjacent whitespace, (space and tabs))

NF means Number of Fields (in the current record). So we're using logic to find the record with the maximum number of Fields, capturing the value of the line '$0', and at the END, we print out the line with the most fields.

It is left undefined what will happen if 2 lines have the same maximum # of commas ;-)

I hope this helps.

like image 38
shellter Avatar answered May 25 '26 18:05

shellter