Bash tool to get nth line from a file

前端 未结 19 2567
刺人心
刺人心 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 09:02

    This question being tagged Bash, here's the Bash (≥4) way of doing: use mapfile with the -s (skip) and -n (count) option.

    If you need to get the 42nd line of a file file:

    mapfile -s 41 -n 1 ary < file
    

    At this point, you'll have an array ary the fields of which containing the lines of file (including the trailing newline), where we have skipped the first 41 lines (-s 41), and stopped after reading one line (-n 1). So that's really the 42nd line. To print it out:

    printf '%s' "${ary[0]}"
    

    If you need a range of lines, say the range 42–666 (inclusive), and say you don't want to do the math yourself, and print them on stdout:

    mapfile -s $((42-1)) -n $((666-42+1)) ary < file
    printf '%s' "${ary[@]}"
    

    If you need to process these lines too, it's not really convenient to store the trailing newline. In this case use the -t option (trim):

    mapfile -t -s $((42-1)) -n $((666-42+1)) ary < file
    # do stuff
    printf '%s\n' "${ary[@]}"
    

    You can have a function do that for you:

    print_file_range() {
        # $1-$2 is the range of file $3 to be printed to stdout
        local ary
        mapfile -s $(($1-1)) -n $(($2-$1+1)) ary < "$3"
        printf '%s' "${ary[@]}"
    }
    

    No external commands, only Bash builtins!

提交回复
热议问题