Bash tool to get nth line from a file

前端 未结 19 2041
刺人心
刺人心 2020-11-22 08:07

Is there a \"canonical\" way of doing that? I\'ve been using head -n | tail -1 which does the trick, but I\'ve been wondering if there\'s a Bash tool that speci

19条回答
  •  隐瞒了意图╮
    2020-11-22 08:47

    Lots of good answers already. I personally go with awk. For convenience, if you use bash, just add the below to your ~/.bash_profile. And, the next time you log in (or if you source your .bash_profile after this update), you will have a new nifty "nth" function available to pipe your files through.

    Execute this or put it in your ~/.bash_profile (if using bash) and reopen bash (or execute source ~/.bach_profile)

    # print just the nth piped in line
    nth () { awk -vlnum=${1} 'NR==lnum {print; exit}'; } 
    

    Then, to use it, simply pipe through it. E.g.,:

    $ yes line | cat -n | nth 5
         5  line
    

提交回复
热议问题