Get specific line from text file using just shell script

前端 未结 10 2102
清酒与你
清酒与你 2020-12-22 16:59

I am trying to get a specific line from a text file.

So far, online I have only seen stuff like sed, (I can only use the sh -not bash or sed or anything like that).

相关标签:
10条回答
  • 2020-12-22 17:34

    Easy with perl! If you want to get line 1, 3 and 5 from a file, say /etc/passwd:

    perl -e 'while(<>){if(++$l~~[1,3,5]){print}}' < /etc/passwd
    
    0 讨论(0)
  • 2020-12-22 17:35

    The standard way to do this sort of thing is to use external tools. Disallowing the use of external tools while writing a shell script is absurd. However, if you really don't want to use external tools, you can print line 5 with:

    i=0; while read line; do test $((++i)) = 5 && echo "$line"; done < input-file
    

    Note that this will print logical line 5. That is, if input-file contains line continuations, they will be counted as a single line. You can change this behavior by adding -r to the read command. (Which is probably the desired behavior.)

    0 讨论(0)
  • 2020-12-22 17:37

    Assuming line is a variable which holds your required line number, if you can use head and tail, then it is quite simple:

    head -n $line file | tail -1
    

    If not, this should work:

    x=0
    want=5
    cat lines | while read line; do
      x=$(( x+1 ))
      if [ $x -eq "$want" ]; then
        echo $line
        break
      fi
    done
    
    0 讨论(0)
  • 2020-12-22 17:42

    I didn't particularly like any of the answers.

    Here is how I did it.

    # Convert the file into an array of strings
    lines=(`cat "foo.txt"`)
    
    # Print out the lines via array index
    echo "${lines[0]}"
    echo "${lines[1]}"
    echo "${lines[5]}"
    
    0 讨论(0)
提交回复
热议问题