简体   繁体   中英

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.

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.

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.

FatalError's FS-based solution is nice. Another way I can think of is to remove non-comma characters from the line, then count its 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's best, of dark and bright
1 Meet in her aspect, and her eyes
[ghoti@pc ~]$ 

Now we just need to keep track of it:

[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 ~]$ 

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}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM