Chinaunix

标题: shell 解析xml的问题 [打印本页]

作者: hyh717    时间: 2014-10-08 14:22
标题: shell 解析xml的问题
需要解析的源文件:

/tmp/cameralist :

<?xml version="1.0" encoding="UTF-8"?>
<cameralist>
  <camera brand="virtual camera" ip="192.168.1.17" mac="000000000000" hasAudio="no" hasVideo="yes">
    <url codec="m4v">rtsp://192.168.1.17:5554/ipcam1.m4v</url>
  </camera>


想要获取IP的值:

grep -Eo "ip=/"[^ ]+/"" /tmp/cameralist | awk -F/" '{print $2}'


想问一下这里哪里出错了,该怎么写! 谢谢~~

作者: ly5066113    时间: 2014-10-08 14:26
回复 1# hyh717
  1. grep -Po '(?<=ip=")[^"]+' /tmp/cameralist
复制代码

作者: hyh717    时间: 2014-10-08 14:39
回复 2# ly5066113

搞定,谢谢··


   
作者: bulletmarquis    时间: 2014-10-08 14:41
回复 1# hyh717
  1. awk -vRS='[ \n]' -vFS='"' '/ip=/{print $2}' file
复制代码

作者: Shell_HAT    时间: 2014-10-08 14:43
  1. sed -r '/ ip=/!d; s/.* ip="([^"]+)".*/\1/' /tmp/cameralist
复制代码

作者: 李满满    时间: 2014-10-08 17:11
学生党:飘过~python试试....谢谢让我明白了re正则的东西~

  1. #!/usr/bin/env python
  2. # -*- coding: gbk -*-
  3. "like grep"
  4. import sys,re
  5. import linecache as lc

  6. pattern=re.compile(r'(?<=ip=")[^"]+')

  7. for line in lc.getlines(sys.argv[1]):
  8.         if re.search(pattern,line):
  9.                 print re.findall(pattern,line)[0]
复制代码
测试:
$ ./yhsafe.py yhsafe.txt
192.168.1.17

作者: reyleon    时间: 2014-10-08 18:16
回复 6# 李满满
  1. python -c "import re;print '\n'.join(re.findall('ip=\"(.*?)\"',open('file').read()))"
复制代码
这样就O啦,发神.
作者: 李满满    时间: 2014-10-08 18:32
一招流~师傅好厉害~.read()默认读取全部~好好这个方法更适合findall函数回复 7# reyleon


   
作者: reb00t    时间: 2014-10-08 18:51
  1. <?php
  2. preg_match('/.*ip="([^"]+)".*/', file_get_contents('200.txt'),$matchs);
  3. echo $matchs[1];
  4. ?>

  5. 192.168.1.17
复制代码

作者: prcardin    时间: 2014-10-09 00:20
grep赞一个
回复 2# ly5066113


   




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2