简体   繁体   中英

Bash: Limit output of ls and grep

Let me present an example and than try to explain my problem:

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

Now I only want to delete the first four results of the above command. Normally if I have to delete all the files I would do ls | grep srt$ | xargs -I {} rm {} ls | grep srt$ | xargs -I {} rm {} ls | grep srt$ | xargs -I {} rm {} but in this case I only want to delete the top four.

So, how can limit the output of ls and grep or suggest me an alternate way to achieve this.

您可以将命令传递给head -n以限制为n行:

ls | grep srt | head -4
$ 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

If you don't have too many files, you can use a bash array:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM