简体   繁体   中英

Save output of bash command for use with pipe command (|)

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!

Use this :

#!/bin/bash

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

Notes :

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