Search code examples
bashshellgrepcut

Print line numbers from grep separated with a comma


I used grep to get the line numbers from a file where a particular string occurred. What if I want these line numbers to appear in on line separated by a comma not vertically in a line?

cFont=$(grep -icE "<font *" $htmlFile)
if [ $cFont -gt 0 ] ; then
  echo "There are $cFont line(s) with <font> tag, they are: " >> ~/Desktop/errors.txt
  grep -inE "<font *" $htmlFile |cut -f1 -d: >> ~/Desktop/errors.txt
fi

The out put was

There are 4 line(s) with <font> tag, they are: 
14
43
46
72

I want it to be

There are 4 line(s) with <font> tag, they are: 
14, 43, 46, 72

Solution

  • Instead of cut -f1 -d: you can use awk:

    awk 'NR > 1 {printf "%s, ", p} {p=$0} END {print p}' file
    
    14, 43, 46, 72