【问题标题】:Save output of bash command for use with pipe command (|)保存 bash 命令的输出以与管道命令 (|) 一起使用
【发布时间】:2019-12-11 21:47:24
【问题描述】:

说我有以下问题

  • 统计文件夹中文件名中带有“a”的文件
  • 重复“e”、“i”和所有其他元音

一种解决方案是:

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)

这工作正常,但该文件夹包含数千个文件。我希望通过在变量中捕获ls 的输出,然后将输出发送到grepwc 来加快速度,但是语法让我失望。

lsCaptured=$(ls)
FilesWithA=$($lsCaptured | grep a | wc -l) #not working!

【问题讨论】:

标签: linux bash


【解决方案1】:

使用这个:

#!/bin/bash

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

 注释:

【讨论】:

  • grep 有-c 计数选项——不需要wc
  • 太棒了,谢谢!正是我需要的。评论中建议的答案没有帮助。请注意,您甚至可以在更复杂的命令中插入here-string,例如FilesWithA=$(grep a &lt;&lt;&lt; "$captured" | wc -l)
猜你喜欢
  • 2012-03-27
  • 2015-12-07
  • 2019-11-08
  • 1970-01-01
  • 1970-01-01
  • 2011-10-15
  • 2021-10-24
  • 2018-08-18
相关资源
最近更新 更多