【问题标题】:Bash: Limit output of ls and grepBash:限制 ls 和 grep 的输出
【发布时间】:2012-10-05 21:12:59
【问题描述】:

让我举一个例子,然后试着解释我的问题:

noob@noob:~/Downloads$ ls | grep srt$
Elementary - 01x01 - Pilot.LOL.English.HI.C.orig.Addic7ed.com.srt
Haven - 01x01 - Welcome to Haven.DVDRip.SAiNTS.English.updated.Addic7ed.com.srt
Haven - 01x01 - Welcome to Haven.FQM.English.HI.C.updated.Addic7ed.com.srt
Supernatural - 08x01 - We Need to Talk About Kevin.LOL.English.HI.C.updated.Addic7ed.com.srt
The Big Bang Theory - 06x02 - The Decoupling Fluctuation.LOL.English.HI.C.orig.Addic7ed.com.srt
Torchwood - 1x01 - Everything changes.0TV.English.orig.Addic7ed.com.srt
Torchwood - 1x01 - Everything changes.divx.English.updated.Addic7ed.com.srt

现在我只想删除上面命令的第一个four results。通常,如果我必须删除所有文件,我会这样做ls | grep srt$ | xargs -I {} rm {},但在这种情况下,我只想删除前四个。

那么,如何限制 ls 和 grep 的输出或建议我另一种方法来实现这一点。

【问题讨论】:

    标签: bash grep ls


    【解决方案1】:

    您可以将您的命令通过管道传输到head -n 以限制为n 行:

    ls | grep srt | head -4
    

    【讨论】:

    • 你为什么不干脆ls *.srt | head -4
    【解决方案2】:
    $ for i in `seq 1 345`; do echo $i ;done | sed -n '1,4p' 
    1
    2
    3
    4
    geee: ~
    $ for i in `seq 1 345`; do echo $i ;done | sed -n '335,360p' 
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    

    【讨论】:

      【解决方案3】:

      如果文件不多,可以使用bash数组:

      matching_files=( *.srt )
      rm "${matching_files[@]:0:4}"
      

      【讨论】:

      • 哈哈,不错。除了无法记住 shell 替换和子字符串扩展的语法的部分。也许这就是我:)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      相关资源
      最近更新 更多