Get specific line from text file using just shell script

前端 未结 10 2100
清酒与你
清酒与你 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:19

    If for example you want to get the lines 10 to 20 of a file you can use each of these two methods:

    head -n 20 york.txt | tail -11
    

    or

    sed -n '10,20p' york.txt 
    

    p in above command stands for printing.

    Here's what you'll see:

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

    In parallel with William Pursell's answer, here is a simple construct which should work even in the original v7 Bourne shell (and thus also places where Bash is not available).

    i=0
    while read line; do
        i=`expr "$i" + 1`
        case $i in 5) echo "$line"; break;; esac
    done <file
    

    Notice also the optimization to break out of the loop when we have obtained the line we were looking for.

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

    Best performance method

    sed '5q;d' file
    

    Because sed stops reading any lines after the 5th one

    Update experiment from Mr. Roger Dueck

    I installed wcanadian-insane (6.6MB) and compared sed -n 1p /usr/share/dict/words and sed '1q;d' /usr/share/dict/words using the time command; the first took 0.043s, the second only 0.002s, so using 'q' is definitely a performance improvement!

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

    sed:

    sed '5!d' file
    

    awk:

    awk 'NR==5' file
    
    0 讨论(0)
  • 2020-12-22 17:30
    line=5; prep=`grep -ne ^ file.txt | grep -e ^$line:`; echo "${prep#$line:}"
    
    0 讨论(0)
  • 2020-12-22 17:32

    You could use sed -n 5p file.

    You can also get a range, e.g., sed -n 5,10p file.

    0 讨论(0)
提交回复
热议问题