Chinaunix

标题: 精确打印20个字符串的行 [打印本页]

作者: byrand1984    时间: 2015-12-17 23:14
标题: 精确打印20个字符串的行
小弟想精确打印文本中只有20个字符串的行,用sed或awk或grep

1234 5678 9101 11221 ##这一行20个字符包含空格的
abcdefghijklmnopqrst   ##这一行20个字符,没有空格

12345 678910 11 22 33 44 55 77 ##这个超过20个字符

作者: songyc_2015    时间: 2015-12-17 23:22
grep -E '^.{20}$' file
作者: jcdiy0601    时间: 2015-12-18 09:34
本帖最后由 jcdiy0601 于 2015-12-18 09:36 编辑
  1. #!/usr/bin/env python
  2. #_*_ coding:utf-8 _*_

  3. f = open('file','r')
  4. list = [x.strip() for x in f.readlines() if len(x) == 21]
  5. for i in list:
  6.         print i
  7. f.close()
复制代码

作者: vagrant_1220    时间: 2015-12-18 09:39
awk '{if(length($0)==20)print $0}' ufile
作者: yjh777    时间: 2015-12-18 09:54
while read l; do [ ${#l} = 20 ] && echo $l; done <file
作者: Herowinter    时间: 2015-12-18 10:15
回复 1# byrand1984

  1. grep -x '.\{20\}' i
  2. 1234 5678 9101 11221
  3. abcdefghijklmnopqrst
复制代码

作者: chengchow    时间: 2015-12-18 13:48
本帖最后由 chengchow 于 2015-12-18 13:48 编辑
  1. sed -rn '/^.{20}$/p' file
  2. awk -F "" 'NF==20' file
复制代码

作者: byrand1984    时间: 2015-12-19 20:15
小弟谢谢楼上的各位大虾

小弟验证过都是可以的
作者: byrand1984    时间: 2015-12-19 20:34
回复 7# chengchow

awk  -F ""  'NF==20' file
小弟对这个命令有些费解,它为什么可以打印出20个字符串的行,特别是NF==20有点深奥
小弟知道NF是number of fields,是列的数量,$NF表示最后一列,NF表示共多少个列

小弟尝试如下的试验,该文本如果以默认的空格作为分隔符号,共有8个列
shanwei:~/awk/pipei # cat zimushuzi
abc001 abc003 hl00b2 hl00b1 i11 i115 i123L004 i123L005
yuwen001 shuxue002 yinyue003 huaxue004 wuli005 meishu006 tiyu007 gongke008

shanwei:~/awk/pipei # awk -F " " '{print NF==3}' zimushuzi  
0
0

小弟原以为,上面的命令可以打印前三列的,即如下的内容

abc001 abc003 hl00b2
yuwen001 shuxue002 yinyue003


   
作者: reyleon    时间: 2015-12-19 20:52
awk 'length==20'
作者: chengchow    时间: 2015-12-30 16:30
回复 9# byrand1984

awk  -F ""  'NF==20' file

技巧在-F ""
定义了awk的列分隔符是任意字符,所以一个字符都是一个列

   




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