題目描述
輸入文字檔案內容,並輸出其前20行。
原題網址
輸入格式
輸入一個文字檔案。
輸出格式
將輸出文字檔案的前20行內容。
範例輸入
From fairest creatures we desire increase, That thereby beauty's rose might never die, But as the riper should by time decease, His tender heir might bear his memory: But thou contracted to thine own bright eyes, Feed'st thy light's flame with self-substantial fuel, Making a famine where abundance lies, Thy self thy foe, to thy sweet self too cruel: Thou that art now the world's fresh ornament, And only herald to the gaudy spring, Within thine own bud buriest thy content, And tender churl mak'st waste in niggarding: Pity the world, or else this glutton be, To eat the world's due, by the grave and thee. When forty winters shall besiege thy brow, And dig deep trenches in thy beauty's field, Thy youth's proud livery so gazed on now, Will be a tattered weed of small worth held: Then being asked, where all thy beauty lies, Where all the treasure of thy lusty days; To say within thine own deep sunken eyes, Were an all-eating shame, and thriftless praise. How much more praise deserved thy beauty's use, If thou couldst answer 'This fair child of mine Shall sum my count, and make my old excuse'
範例輸出
From fairest creatures we desire increase, That thereby beauty's rose might never die, But as the riper should by time decease, His tender heir might bear his memory: But thou contracted to thine own bright eyes, Feed'st thy light's flame with self-substantial fuel, Making a famine where abundance lies, Thy self thy foe, to thy sweet self too cruel: Thou that art now the world's fresh ornament, And only herald to the gaudy spring, Within thine own bud buriest thy content, And tender churl mak'st waste in niggarding: Pity the world, or else this glutton be, To eat the world's due, by the grave and thee. When forty winters shall besiege thy brow, And dig deep trenches in thy beauty's field, Thy youth's proud livery so gazed on now, Will be a tattered weed of small worth held: Then being asked, where all thy beauty lies, Where all the treasure of thy lusty days;
解題概念
利用while和「read」指令,來一行一行讀取從標準輸入傳進來的檔案內容。每讀取到一行資料,就儲存到變數C之中,再串接到TEST變數之後,以此來讀取完整的檔案內容。接著將TEST變數作為「head」指令的輸入來輸出結果。「head」指令可以讀取文字資料。並利用「-n」選項指定來輸出資料前幾行的內容。
參考答案
#!/bin/bash
read C
TEXT=${C}
while read C; do
TEXT="${TEXT}\n${C}"
done
printf "${TEXT}" | head -n 20