Bash tool to get nth line from a file

前端 未结 19 2098
刺人心
刺人心 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:44

    head and pipe with tail will be slow for a huge file. I would suggest sed like this:

    sed 'NUMq;d' file
    

    Where NUM is the number of the line you want to print; so, for example, sed '10q;d' file to print the 10th line of file.

    Explanation:

    NUMq will quit immediately when the line number is NUM.

    d will delete the line instead of printing it; this is inhibited on the last line because the q causes the rest of the script to be skipped when quitting.

    If you have NUM in a variable, you will want to use double quotes instead of single:

    sed "${NUM}q;d" file
    

提交回复
热议问题