修改grep结果以打印匹配字符串中的特定单词

时间:2018-09-28 08:47:19

标签: shell grep

我有一个grep输出,如下所示:

Path to log files = /data/db2inst1/NODE0000/SQL00001/LOGSTREAM0000/
Database is in write suspend state = YES
Path to log files = /data/db2inst1/NODE0001/SQL00001/LOGSTREAM0001/
Database is in write suspend state = NO

我要对此进行如下编辑:

Node = NODE0000
Database is in write suspend state = YES
Node = NODE0001
Database is in write suspend state = NO

有可能吗?

3 个答案:

答案 0 :(得分:2)

您无需保留grep的流水线即可生成所需的输出。 Awkgrep强大一点,它可以让您对匹配的文本进行转换,这非常强大。因此,您所需的示例便是

awk '/Path to log files/{match($0,/NODE([^/]+)/,a); printf "Node = NODE%s\n",a[1];next}
    /Database is in write suspend state/' file

答案 1 :(得分:0)

$  awk -F"/" '{if(NR!=1) if($1 ~ /Path to log files/) print $1,$4 ;else print ;else print "Node = "$4 }' temp
Node = NODE0000
Database is in write suspend state = YES
Path to log files =  NODE0001
Database is in write suspend state = NO

答案 2 :(得分:0)

使用sed(也可以替换您的grep命令):

sed -n '/^Database is in write suspend state/p;
        /^Path to log files = /s|.*/.*\(NODE[0-9]\+\).*/$|Node = \1|p' file