解析标准输出和运行命令如果行匹配
问题描述:
我想分析一个命令的标准输出并运行命令,如果一行匹配。以例如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
答
一个简单的脚本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
步骤: -
- 读文件中的行由行
- 如果线路带“B”开始,追加字符串根据需要,否则其追加这样
- 为了避免无用的使用“猫”命令
<(file)
过程的3'-取代做
echo
有-e
标志来启用在这种情况下,特殊字符\n
解释。
您可以通过在匹配它们的&&
部分之后替换echo
并在||
条件之后替换非匹配行来运行匹配行的其他命令。我已经在下面用虚拟命令名称cmd_for_matching_lines
和cmd_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
答
的便携式解决方案,而无需bash化如[[ ]]
,我会写为
#!/bin/sh
while read city; do
case $city in
(b*) echo $city starts with b;;
esac
done < cities.txt
注意这是怎么容易地扩展到不区分大小写(使用([Bb]*)
代替),并与测试,以增加为其他首字母缩写。
也许这样使用[AWK](https://www.gnu.org/software/gawk/manual/gawk.html)?实验! –
@shellter是的,这是一个愚蠢的例子,但想法是,当它匹配时我需要执行另一个命令。 –