Max comma on one line using bash script
I have \n
end text :
She walks, in beauty, like the night Without clouds, stars and stars And all the best of the dark and bright Meet in her aspect and her eyes.
And I want to find which line has the maximum number ,
and print that line too. For example, the text above should look like
She walks in beauty like the night
Since it has 2 (maximum among all strings) comma.
I tried:
cat p.txt | grep ','
but don't know where to go.
source to share
try it
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',' F says use ',' to separate fields. (The default for F is adjacent space, (space and tabs))
NF stands for the number of fields (in the current record). So we use logic to find the record with the maximum number of fields, fixing the value of the string "$ 0", and in END we print the string with the most fields.
It remains undefined, which happens if two strings have the same maximum number of commas; -)
Hope this helps.
source to share
The FatalError FS solution is good. Another way I can think of is to remove non-comma characters from the string and then count the length:
[ghoti@pc ~]$ awk '{t=$0; gsub(/[^,]/,""); print length($0), t;}' poem
2 She walks, in beauty, like the night
1 Of cloudless climes, and starry skies
1 And all that best, of dark and bright
1 Meet in her aspect, and her eyes
[ghoti@pc ~]$
Now we just need to track this:
[ghoti@pc ~]$ awk '{t=$0;gsub(/[^,]/,"");} length($0)>max{max=length($0);line=t} END{print line;}' poem
She walks, in beauty, like the night
[ghoti@pc ~]$
source to share
Pure Bash:
declare ln=0 # actual line number
declare maxcomma=0 # max number of commas seen
declare maxline='' # corresponding line
while read line ; do
commas="${line//[^,]/}" # remove all non-commas
if [ ${#commas} -gt $maxcomma ] ; then
maxcomma=${#commas}
maxline="$line"
fi
((ln++))
done < "poem.txt"
echo "${maxline}"
source to share