【问题标题】:How to merge these codes, awk then cut如何合并这些代码,awk然后cut
【发布时间】:2016-09-14 00:30:22
【问题描述】:

我在 Debian 中使用 awk。

输入

11.22.33.44#55878:
11.22.33.43#55879:
...
...
(smtp:55.66.77.88)
(smtp:55.66.77.89)
...
...
cpe-33-22-11-99.buffalo.res.rr.com[99.11.22.33]
cpe-34-22-11-99.buffalo.res.rr.com[99.11.22.34]
...

部分 sh 代码(在 Debian 中运行)

awk '/#/ {print > "file1";next} \
/smtp/ {print > "file2";next} \
{print > "file7"}' input
#
if [ -s file1 ] ; then
    #IP type => 11.22.33.44#55878:
    cut -d'#' -f1 file1 >> output
    rm -f file1
fi
#
if [ -s file2 ] ; then
    #IP type => (smtp:55.66.77.88)
    cut -d':' -f2 file2 | cut -d')' -f1 >> output
    rm -f file2
fi
#
if [ -s file7 ] ; then
    #IP type => cpe-33-22-11-99.buffalo.res.rr.com[99.11.22.33]
    cut -d'[' -f2 file7 | cut -d']' -f1 >> output
    rm -f file7
fi

然后输出

11.22.33.44
11.22.33.43
55.66.77.88
55.66.77.89
99.11.22.33
99.11.22.34

是否可以仅将这些代码与 awk 合并,例如

awk '/#/ {print | cut -d'#' -f1 > "file1";next} \
/smtp/ {print | cut -d':' -f2 | cut -d')' -f1 > "file2";next} \
{print | cut -d'[' -f2 file7 | cut -d']' > "file7"}' input

我是新手,对此一无所知, 搜索问题后,仍然没有帮助。 任何提示? 谢谢。

最好的问候。

【问题讨论】:

    标签: awk cut


    【解决方案1】:
    $ awk -F'[][()#]|smtp:' '/#/{print $1;next} /smtp/{print $3;next} /\[/{print $2}' input
    11.22.33.44
    11.22.33.43
    55.66.77.88
    55.66.77.89
    99.11.22.33
    99.11.22.34
    

    要将其保存在文件output中:

    awk -F'[][()#]|smtp:' '/#/{print $1;next} /smtp/{print $3;next} /\[/{print $2}' input >output
    

    工作原理

    • -F'[][()#]|smtp:'

      这会将字段分隔符设置为 (a) 任何字符 ][()# 或 (b) 字符串 smtp:

    • /#/{print $1;next}

      如果该行包含#,则打印第一个字段并跳到next 行。

    • /smtp/{print $3;next}

      如果该行包含smtp,则打印第三个字段并跳到next 行。

    • /\[/{print $2}

      如果该行包含[,则打印第二个字段。

    变化

    解决这个问题的方法不止一种,例如,使用稍微不同的字段分隔符,我们仍然可以得到想要的输出:

    $ awk -F'[][()#:]' '/#/{print $1;next} /smtp/{print $3;next} /\[/{print $2}' input
    11.22.33.44
    11.22.33.43
    55.66.77.88
    55.66.77.89
    99.11.22.33
    99.11.22.34
    

    【讨论】:

    • 嗨约翰,这是一个很好的答案。但我想知道,有什么区别:A:-F'[][()#]|smtp:'B:-F' [[]()#]|smtp:'为什么A工作,B不工作?
    • @NamPham 谢谢。将方括号放在方括号内有一些特殊规则。通常,例如,] 将终止分组。例外情况是它是组中的第一个字符。因此[]abc]]abc 中的任何一个。相比之下,[[]abc] 正则表达式 [[]a] 匹配字符序列 [ 后跟 a 后跟 ]
    • @John 感谢您如此详细的回答。
    猜你喜欢
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 2017-05-14
    相关资源
    最近更新 更多