Chinaunix

标题: awk 如何判断截取的某一个字符串为空?? [打印本页]

作者: ryr1990    时间: 2014-08-26 20:10
标题: awk 如何判断截取的某一个字符串为空??
例子:
aaaa|  |hello|world|
aaa|bbbb|ccc|ddd|

如何判断以"|"间隔的第二个字符串为空,然后打印出来?

作者: reb00t    时间: 2014-08-26 20:32
  1. <?php

  2. if(file_exists("200.txt")){

  3.   $f = fopen('200.txt','r');
  4.    while(!feof($f)){
  5.           $line = fgets($f);
  6.       $arr=explode('|', $line);
  7.       
  8.      if (strlen($arr[1]) == 0){
  9.               print $line;
  10.     }   

  11.     }
  12. }else{

  13.         echo "file is not find";
  14. }

  15. ?>
  16. 结果是
  17. aaaa||hello|world|
  18. [Finished in 0.2s]
复制代码

作者: lifayi2008    时间: 2014-08-26 20:41
本帖最后由 lifayi2008 于 2014-08-26 20:46 编辑
  1. awk -F'|' '$2~/ +/{print}' c.txt
复制代码

作者: love_shift    时间: 2014-08-26 23:07
  1. root@ubuntu:~/test# more file
  2. aaaa|  |hello|world|
  3. aaa|bbbb|ccc|ddd|
  4. root@ubuntu:~/test# awk -F'|' '$2<0' file
  5. aaaa|  |hello|world|
复制代码
  1. >>> import re
  2. >>>
  3. >>> def iter(f):
  4. ...     s = f.readline().strip()
  5. ...     while s:
  6. ...           yield s
  7. ...           s = f.readline().strip()
  8. ...
  9. >>> with open('file','r') as f:
  10. ...      for j in iter(f):
  11. ...          if re.search(' +',j.split('|')[1]):
  12. ...             print j
  13. ...
  14. aaaa|  |hello|world|
复制代码

作者: yestreenstars    时间: 2014-08-26 23:38
@lifayi2008

不谨慎~
  1. awk -F\| '$2~/^ *$/'
复制代码

作者: lifayi2008    时间: 2014-08-27 10:04
{:2_168:} 是应该这样写,昨晚还想不通为啥 $2~/ */匹配不到呢回复 5# yestreenstars


   
作者: love_shift    时间: 2014-08-27 10:11
回复 6# lifayi2008

* 号可以代表0个,就是没空了


   
作者: li0924    时间: 2014-08-27 11:07
  1. awk -F"|" '! $2 && $2 != 0' file
复制代码

作者: tasteoftime_90    时间: 2014-08-27 16:18
大神 awk -F '|' '{if($2~/^ *$/){print ;}}' 这个为什么改成 awk -F '|' '{if($2~/^\s*$/){print ;}}' 就不可以了?
回复 5# yestreenstars


   
作者: yestreenstars    时间: 2014-08-27 16:23
回复 9# tasteoftime_90

awk不支持\s
   
作者: Herowinter    时间: 2014-08-27 16:24
本帖最后由 Herowinter 于 2014-08-27 16:24 编辑

回复 9# tasteoftime_90

较老版本awk  \s改成[[:space:]]

   
作者: tasteoftime_90    时间: 2014-08-27 17:09
明白 回复 11# Herowinter


   




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