Unix - 从字符串中提取单词

时间:2013-12-20 12:57:32

标签: unix awk grep

需要一些unix脚本的帮助

我的文件如下所示:

certificate: DPCert_CryptoCer [up]
certificate: ELABpreprod_CA1V2_CER [up]
certificate: ELABpreprod_CA2V2_CER [up]
certificate: ELABpreprod_PUBROOT_CER [up]
certificate: hbosIssuerCert [up]
certificate: hbosRootCert [up]
certificate: MQ_CryptoCer [up]

我的脚本应该只将以下内容输出到文件中:

DPCert_CryptoCer
ELABpreprod_CA1V2_CER
ELABpreprod_CA2V2_CER 
ELABpreprod_PUBROOT_CER
hbosIssuerCert 
hbosRootCert
MQ_CryptoCer

任何有关sed / awk / grep的帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

如果要打印第二个字段,请使用:

$ awk '{print $2}' file
DPCert_CryptoCer
ELABpreprod_CA1V2_CER
ELABpreprod_CA2V2_CER
ELABpreprod_PUBROOT_CER
hbosIssuerCert
hbosRootCert
MQ_CryptoCer

如果您需要的是倒数第二个字段,请使用:

$ awk '{print $(NF-1)}' file
DPCert_CryptoCer
ELABpreprod_CA1V2_CER
ELABpreprod_CA2V2_CER
ELABpreprod_PUBROOT_CER
hbosIssuerCert
hbosRootCert
MQ_CryptoCer

要将内容保存到另一个文件中,请重定向命令:

awk '{print $2}' file > new_file

awk '{print $(NF-1)}' file > new_file

使用grep

$ grep -Po '(?<=certificate: )[^[]*' file
DPCert_CryptoCer 
ELABpreprod_CA1V2_CER 
ELABpreprod_CA2V2_CER 
ELABpreprod_PUBROOT_CER 
hbosIssuerCert 
hbosRootCert 
MQ_CryptoCer 

它会打印certificate:之后的所有内容以及[字符。

答案 1 :(得分:1)

尝试sed

sed -r 's/.* (.*) .*/\1/' file

如果字段由空字符分隔,并且您想获得第二个字段,则可以使用剪切

cut -d' ' -f2 file
相关问题