Bash tool to get nth line from a file

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

    I've put some of the above answers into a short bash script that you can put into a file called get.sh and link to /usr/local/bin/get (or whatever other name you prefer).

    #!/bin/bash
    if [ "${1}" == "" ]; then
        echo "error: blank line number";
        exit 1
    fi
    re='^[0-9]+$'
    if ! [[ $1 =~ $re ]] ; then
        echo "error: line number arg not a number";
        exit 1
    fi
    if [ "${2}" == "" ]; then
        echo "error: blank file name";
        exit 1
    fi
    sed "${1}q;d" $2;
    exit 0
    

    Ensure it's executable with

    $ chmod +x get
    

    Link it to make it available on the PATH with

    $ ln -s get.sh /usr/local/bin/get
    

    Enjoy responsibly!

    P

提交回复
热议问题