0

I have a program that counts lines containing alphanumeric words. For example:

this is line1
this is line
1234
this is line4

The answer is 2.

count=0
while IFS= read -r line
do
    if [[ $line =~  [[:digit:]] ]];
    then
        if [[ $line =~ [a-zA-Z]  ]];
        then
            count=$((count+1))
        fi
    fi
    echo "$( cat $1 )"
done <<< $( cat $1 )
echo "Count: $count"

It works but I don't understand it. What does done <<< $( cat $1 ) do?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • What part of it is unclear? Do you need to know what `<<<` does, or what `$(...)` does, or what `cat` does? I believe we have existing Q&A entries explaining all three. – Charles Duffy Jun 11 '20 at 16:35
  • Mind you, it's not _good_ code; it's very needlessly inefficient. [BashFAQ #1](http://mywiki.wooledge.org/BashFAQ/001) describes the better way to read a file line-by-line, which is also given in the answer by Gilles. – Charles Duffy Jun 11 '20 at 16:39
  • @CharlesDuffy I am not clear what $( cat $1 ) does in the above code? – Divya Chauhan Jun 11 '20 at 16:40
  • `$(...anything...)` is replaced with the output of `...anything...` (potentially subject to some unwanted processes like string-splitting and glob expansion depending on the context, shell version, and how it's quoted). And `cat somefile` runs a program `cat` that reads the file `somefile` and writes its output to stdout. – Charles Duffy Jun 11 '20 at 16:41
  • It is a Here, stdin being fed, in this case by the output of a command, cat $1. https://www.gnu.org/software/bash/manual/html_node/Redirections.html – David G. Pickett Jun 11 '20 at 16:42
  • (also, `cat $1` splits the contents of `$1` on spaces and expands globs in *that* to get the list of arguments to pass to `cat`, so that itself is buggy; `cat -- "$1"` is more reliable). – Charles Duffy Jun 11 '20 at 16:42
  • ...but using `cat` at all is extremely silly here when you could just use `<"$1"` instead and have the loop reading straight from your file, not from a temporary file written with the output of a `cat` program that is _itself_ reading from the file. – Charles Duffy Jun 11 '20 at 16:45
  • I got your point, what you are trying to explain me , thank you @CharlesDuffy – Divya Chauhan Jun 11 '20 at 17:02
  • Using a **here-string** with process substitution that just calls `cat` is a code smell. That whole last part can just be `done < "$1"` – SiegeX Jun 11 '20 at 17:14
  • @SiegeX , I came too know about that few minutes back & rectified it, code works fine now – Divya Chauhan Jun 11 '20 at 17:32

0 Answers0