首页 > 解决方案 > bash - 在读取时与 grep 结合并剪切

问题描述

我想修改我现有的 bash 脚本。这是它现在的样子:

#! /bin/bash    
SAMPLE = myfile.txt

while read SAMPLE
do
    name = $SAMPLE
    # some other code
done < $SAMPLE

在这种情况下,'myfile'.txt 仅包含一列,其中包含我需要的所有信息。

现在我想修改这个脚本,因为“myfile.txt”现在包含比我需要的更多的列和更多的行。

grep 'TEST' myfile.txt | cut -d "," -f 1

给我我需要的价值观。但是我怎样才能将它集成到我的 bash 脚本中呢?

标签: bash

解决方案


您可以将任何命令的输出通过管道传输到while read循环中。

试试这个:

#! /bin/bash    
INPUT=myfile.txt

grep 'TEST' $INPUT | 
cut -d "," -f 1 | 
while read SAMPLE
do
    name=$SAMPLE
    # some other code
done

推荐阅读