Chinaunix

标题: 请教以下sed/awk语句怎么解读 [打印本页]

作者: ahdong2007    时间: 2014-07-28 06:20
标题: 请教以下sed/awk语句怎么解读

1)这里的 0 ~ 2是什么意思呀?
sed '0~2 {=;d}' /etc/passwd

2) 这里,最后面的1怎么理解?
seq 10|awk '{if($0==5)next}1'


谢谢!  
作者: q1208c    时间: 2014-07-28 07:51
Try it first.
作者: ahdong2007    时间: 2014-07-28 08:01
回复 2# q1208c


    我问问题之前我当然试过,知道结果不是最重要的,知道为什么才是最重要的,你说呢?
作者: Herowinter    时间: 2014-07-28 08:03
回复 1# ahdong2007

1.
  1. [masonzhu@rat122 ~]$ seq 10|sed -n '0~2p'
  2. 2
  3. 4
  4. 6
  5. 8
  6. 10
  7. [masonzhu@rat122 ~]$ seq 10|sed -n '1~2p'
  8. 1
  9. 3
  10. 5
  11. 7
  12. 9
复制代码
2.   "1"等价于下面的代码
{if(1)print $0}
作者: ahdong2007    时间: 2014-07-28 08:10
回复 4# Herowinter


    非常感谢!
    请问,关于这个的说明,在哪些资料上有呀?我读了 sed & awk,也没有看到对 0 ~ 2这种用法的说明。

    对于 2),我也实验过,只要不是0,输出都是一样的,也大概猜测是有if判断,加上默认的print行为,只是没有找到出处。

    再次感谢!
作者: Herowinter    时间: 2014-07-28 08:20
本帖最后由 Herowinter 于 2014-07-28 08:22 编辑

回复 5# ahdong2007
1. info sed,一般info的资料比较全,我这里英文版的,你可以看一下自己的。
  1. `FIRST~STEP'
  2.      This GNU extension matches every STEPth line starting with line
  3.      FIRST.  In particular, lines will be selected when there exists a
  4.      non-negative N such that the current line-number equals FIRST + (N
  5.      * STEP).  Thus, to select the odd-numbered lines, one would use
  6.      `1~2'; to pick every third line starting with the second, `2~3'
  7.      would be used; to pick every fifth line starting with the tenth,
  8.      use `10~5'; and `50~0' is just an obscure way of saying `50'.
复制代码
2. 每一个awk代码块的结果可以分为两块,大概这样的: 条件{行为}
当其中某一部分缺失时,用默认条件或默认行为,默认的条件是true,默认的行为
是print $0;代码最后写了个1就是省略了行为的写法,条件是1(true),行为是
默认行为,以前论坛有个讲这个帖子的,一下子找不到。

   
作者: jason680    时间: 2014-07-28 08:34
本帖最后由 jason680 于 2014-07-28 08:35 编辑

@Herowinter @ahdong2007

[电子书下载]ChinaUnix论坛Shell版精华帖合集(2011-04-30更新)
http://bbs.chinaunix.net/forum.p ... mp;fromuid=24785593

awk初学之常见问题
http://bbs.chinaunix.net/forum.p ... mp;fromuid=24785593

作者: ahdong2007    时间: 2014-07-28 08:44
回复 6# Herowinter


    谢谢您的耐心解答!
作者: ahdong2007    时间: 2014-07-28 08:44
回复 7# jason680


    谢谢!
作者: jeffreyst    时间: 2014-07-28 09:02
不错,好贴,mark~
作者: q1208c    时间: 2014-07-28 09:35
回复 3# ahdong2007

如果你真的试过, sed的那个就一定不用问了.  man sed, 就有相关的说明.

awk的那个, 确实如果没人提示, 是不会明白的.
   
下面是 man sed 的部分输出.
  1.        first~step
  2.               Match every step’th line starting with line first.  For example,
  3.               ‘‘sed -n 1~2p’’ will print all the  odd-numbered  lines  in  the
  4.               input  stream,  and the address 2~5 will match every fifth line,
  5.               starting with the second.  first can be zero; in this case,  sed
  6.               operates as if it were equal to step.  (This is an extension.)
复制代码

作者: ahdong2007    时间: 2014-07-28 09:42
回复 11# q1208c


    好吧 ,到目前为止,我只读过  sed & awk,没有读过 sed的man page。
   
    谢谢!




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