1

Say I have the following problem

  • Count the files in the folder which have an "a" in the filename
  • Repeat for "e", "i" and all the other vowels

One solution is:

FilesWithA=$(ls | grep a | wc -l)
FilesWithE=$(ls | grep e | wc -l)
FilesWithI=$(ls | grep i | wc -l)
FilesWithO=$(ls | grep o | wc -l)
FilesWithU=$(ls | grep u | wc -l)

This works fine, but the folder contains many thousands of files. I'm looking to speed this up by capturing the output of ls in a variable, then sending the output to grep and wc, but the syntax is defeating me.

lsCaptured=$(ls)
FilesWithA=$($lsCaptured | grep a | wc -l) #not working!
AlainD
  • 5,413
  • 6
  • 45
  • 99
  • 1
    `grep a <<<“$lsCaptured”` – Jim Danner Dec 11 '19 at 21:50
  • Possible duplicate of [Capturing multiple line output into a Bash variable](https://stackoverflow.com/questions/613572/capturing-multiple-line-output-into-a-bash-variable), or [How to preserve line breaks when storing a command output to a variable in bash](https://stackoverflow.com/questions/22101778/how-to-preserve-line-breaks-when-storing-a-command-output-to-a-variable-in-bash) – oguz ismail Dec 11 '19 at 23:26
  • @oguzismail: None of those gave the `<<<` or `here-string` operator, which worked for me. – AlainD Dec 14 '19 at 11:12

1 Answers1

3

Use this :

#!/bin/bash

captured="$(printf '%s\n' *)"
filesWithA=$(grep -c a <<< "$captured")

 Notes :

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • grep has the `-c` option for counting -- no need for `wc`. – Socowi Dec 11 '19 at 22:04
  • Awesome, thanks! Just what I needed. The answers suggested in a comment were not helpful. Note that you can insert the `here-string` even in more complex commands such as `FilesWithA=$(grep a <<< "$captured" | wc -l)`. – AlainD Dec 12 '19 at 11:12