Bash tool to get nth line from a file

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

    After taking a look at the top answer and the benchmark, I've implemented a tiny helper function:

    function nth {
        if (( ${#} < 1 || ${#} > 2 )); then
            echo -e "usage: $0 \e[4mline\e[0m [\e[4mfile\e[0m]"
            return 1
        fi
        if (( ${#} > 1 )); then
            sed "$1q;d" $2
        else
            sed "$1q;d"
        fi
    }
    

    Basically you can use it in two fashions:

    nth 42 myfile.txt
    do_stuff | nth 42
    

提交回复
热议问题