从shell脚本中的文件中提取数据

时间:2017-03-20 14:19:34

标签: shell

我在文件中有很多数据,如下所示

if(mobile is = Android) show this content

elseif
    this content

2 个答案:

答案 0 :(得分:0)

尝试以下方法:

sed -re 's/^.*created_at ([0-9_]+).*updated_at ([0-9_]+).*$/\1, \2/' input.txt

input.txt

alert tcp any any -> any any (msg: "test1"; sid:16521; rev:1;created_at 2010_07_30, updated_at 2016_07_01;)
alert tcp any any -> any any (msg: "test2"; nocase; distance:0; sid:16521; rev:1;created_at 2010_10_30, updated_at 2013_07_11;)
alert tcp any any -> any any (msg: "test3"; file_data; content:"clsid"; nocase; distance:0; created_at 2008_08_03, updated_at 2016_05_01;

输出:

2010_07_30, 2016_07_01
2010_10_30, 2013_07_11
2008_08_03, 2016_05_01

更多循序渐进的方法可能如下所示:

cat input.txt \
    | grep -Eo '(created|updated)_at [0-9_]+' \
    | cut -d ' ' -f 2 \
    | sed 'N;s/\n/, /'

我们使用grep仅输出与给定正则表达式(created|updated)_at [0-9_]+匹配的数据:

  • (created|updated)_at - 匹配文字' created_at'或文本<; updated_at'
  • 紧接着一个空格,然后是该组中的多个字符:0123456789_

中期产出:

created_at 2010_07_30
updated_at 2016_07_01
created_at 2010_10_30
updated_at 2013_07_11
created_at 2008_08_03
updated_at 2016_05_01
然后使用

cut仅获取第二个字段(-f 2),由空格(-d ' ')分隔。

输出:

2010_07_30
2016_07_01
2010_10_30
2013_07_11
2008_08_03
2016_05_01

最后,sed用于将每两行连接在一起(N),并用逗号空格(s/\n/, /)替换换行符。

输出:

2010_07_30, 2016_07_01
2010_10_30, 2013_07_11
2008_08_03, 2016_05_01

答案 1 :(得分:0)

awk可以做得更简单一些:

awk 'NF{gsub(/[;)]/,"");print $(NF-2),$NF}' file

NF - 所以我们只对具有数据的字段进行操作

gsub - 摆脱最后一项

的一些guff

打印第三个最后一个和最后一个项目

相关问题