迭代文件直到匹配并找到第二个不同的匹配,直到不匹配。重复直到EOF

时间:2016-01-21 20:49:55

标签: bash if-statement recursion grep xargs

嗨,我正在运行的盐脚本中有一个相当大但很混乱的输出。

基本上我最干净的输出如下:

MINION:server1.xyz.com
MINION:server2.xyz.com
MINION:server3.xyz.com
filer1:/vol/storagestuffs/volpath1
filer1:/vol/storagestuffs/volpath2
filer1:/vol/storagestuffs/volpath3
filer1:/vol/storagestuffs/volpath4
MINION:server4.xyz.com
filer4:/vol/storagestuffs/volpath1
MINION:server5.xyz.com
MINION:server6.xyz.com
MINION:server7.xyz.com
filer3:/vol/storagestuffs/volpath1

我想要的只是返回在其下面有文件管理器的仆从以及它们下面的所有文件管理器,我想将其格式化为:

MINION:server3.xyz.com filer1:/vol/storagestuffs/volpath1 
MINION:server3.xyz.com filer1:/vol/storagestuffs/volpath2
MINION:server3.xyz.com filer1:/vol/storagestuffs/volpath3
MINION:server3.xyz.com filer1:/vol/storagestuffs/volpath4
MINION:server4.xyz.com filer4:/vol/storagestuffs/volpath1
MINION:server7.xyz.com filer3:/vol/storagestuffs/volpath1

我调查过if语句,递归语句等等。我要么无法理解bash递归语句,要么就是我不想做的事情。我希望找到一种有效的方法,而不必多次扫描文件。

使用xargs有一种棘手的方法吗? grep中有什么可以做到的吗?

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您可以使用awk:

awk '/^MINION:/{m=$0} /^filer/{print m, $0}' file
MINION:server3.xyz.com filer1:/vol/storagestuffs/volpath1
MINION:server3.xyz.com filer1:/vol/storagestuffs/volpath2
MINION:server3.xyz.com filer1:/vol/storagestuffs/volpath3
MINION:server3.xyz.com filer1:/vol/storagestuffs/volpath4
MINION:server4.xyz.com filer4:/vol/storagestuffs/volpath1
MINION:server7.xyz.com filer3:/vol/storagestuffs/volpath1

答案 1 :(得分:2)

仅限Bash的解决方案是:

minions_with_filers () 
{ 
    label=;
    while IFS=: read -r a b; do
        case $a in 
            MINION)
                label=$a:$b
            ;;
            filer[0-9]*)
                printf '%s %s:%s\n' "$label" "$a" "$b"
            ;;
        esac
    done
}

虽然, @anubhava 的解决方案运行速度要快10倍。

使用示例:

$ minions_with_filers < foo.txt 
MINION:server3.xyz.com filer1:/vol/storagestuffs/volpath1
MINION:server3.xyz.com filer1:/vol/storagestuffs/volpath2
MINION:server3.xyz.com filer1:/vol/storagestuffs/volpath3
MINION:server3.xyz.com filer1:/vol/storagestuffs/volpath4
MINION:server4.xyz.com filer4:/vol/storagestuffs/volpath1
MINION:server7.xyz.com filer3:/vol/storagestuffs/volpath1