2016-09-20 129 views
0

我想分析一个命令的标准输出并运行命令,如果一行匹配。以例如cat cities.txt输出解析标准输出和运行命令如果行匹配

paris 
amsterdam 
munich 
berlin 
london 
brussels 

我想响应这个相同的列表,但以字母B开始任何一个城市运行的命令。

cat cities.txt | <command here ... echo $city starts with b> 

应该输出像

paris 
amsterdam 
munich 
berlin 
berlin starts with b 
london 
brussels 
brussels starts with b 
+1

也许这样使用[AWK](https://www.gnu.org/software/gawk/manual/gawk.html)?实验! –

+0

@shellter是的,这是一个愚蠢的例子,但想法是,当它匹配时我需要执行另一个命令。 –

回答

2

一个简单的脚本bash本: -

#!/bin/bash 

while IFS= read -r line 
do 
    [[ $line == b* ]] && echo -e "$line\n$line starts with b" || echo "$line" 
done <file 

运行脚本产生

$ bash script.sh 
paris 
amsterdam 
munich 
berlin 
berlin starts with b 
london 
brussels 
brussels starts with b 

步骤: -

  1. 读文件中的行由行
  2. 如果线路带“B”开始,追加字符串根据需要,否则其追加这样
  3. 为了避免无用的使用“猫”命令<(file)过程的3'-取代做

echo-e标志来启用在这种情况下,特殊字符\n解释。

您可以通过在匹配它们的&&部分之后替换echo并在||条件之后替换非匹配行来运行匹配行的其他命令。我已经在下面用虚拟命令名称cmd_for_matching_linescmd_for_non_matching_lines进行了演示。

#!/bin/bash 

while IFS= read -r line 
do 
    [[ $line == b* ]] && cmd_for_matching_lines "$line" || cmd_for_non_matching_lines "$line" 
done <file 
2

的便携式解决方案,而无需bash化如[[ ]],我会写为

#!/bin/sh 
while read city; do 
    case $city in 
    (b*) echo $city starts with b;; 
    esac 
done < cities.txt 

注意这是怎么容易地扩展到不区分大小写(使用([Bb]*)代替),并与测试,以增加为其他首字母缩写。

相关问题