題目描述

顯示每行輸入的前3個單字(words)。每個單字間均使用空格進行分隔。



原題網址

輸入格式

輸入一個有著N行ASCII字元的文字檔案。N的範圍在1~100之間(包括1和100)。每行文字都是一個句子,其中的單字均使用空格進行分隔。

輸出格式

將輸入的N行文字中的前3個單字(words),輸出成新的N行。

範例輸入

New York is a state in the Northeastern and Mid-Atlantic regions of the United States.
New York is the 27th-most extensive, the third-most populous populated of the 50 United States.
New York is bordered by New Jersey and Pennsylvania to the south.
About one third of all the battles of the Revolutionary War took place in New York.
Henry Hudson's 1609 voyage marked the beginning of European involvement with the area.

範例輸出

New York is
New York is
New York is
About one third
Henry Hudson's 1609

解題概念

利用while和「read」指令,來一行一行讀取從標準輸入傳進來的檔案內容。每讀取到一行資料,就儲存到變數C之中,再作為輸入傳給「cut」指令來進行字串處理。「cut」指令的「-f」選項可以顯示指定位置的欄位(field)。,如果要指定一段位置範圍內的欄位,可以使用逗號「-」來分隔起始位置和終止位置。不過由於這題的起始位置是從1開始,因此也可以省略起始位置。至於欄位的切割依據,可以使用「cut」指令的「-d」選項來指定使用空格字元來作為切割依據。

參考答案

#!/bin/bash

while read C; do
   cut -d ' ' -f-3 <<< ${C}
done