2017-01-16 38 views

回答

1

我將模擬data.txt文件,

datatxt="Line 1 without colon 
I want this:the part before the colon 
nope, not me 
other line with colon:that can be found" 

你的命令顯示所有行的第一場

echo "${datatxt}" | cut -f 1 -d ":" 
Line 1 without colon 
I want this 
nope, not me 
other line with colon 

當您使用grep第一你可以得到:行:

echo "${datatxt}" | grep ":" | cut -f 1 -d ":" 
I want this 
other line with colon 

您可以爲一行輸出附加| head -1
這些說明也可以用sed來完成。 使用sed可以冒號後刪除一切:

echo "${datatxt}" | sed 's/:.*//' 
Line 1 without colon 
I want this 
nope, not me 
other line with colon 

sed添加的grep可以通過尋找與/:/線來完成。
您應該將其與-np結合使用。

echo "${datatxt}" | sed -n '/:/ s/:.*//p' 
I want this 
other line with colon 

當你想要一個線路輸出,你可以使用

echo "${datatxt}" | sed -n '/:/ s/:.*//p' | sed -n '1p' 
# OR SHORTER 
echo "${datatxt}" | sed -n '/:/ {s/:.*//p;q}' 
1

如果您正在根據行號選擇一行,那麼您可以使用sed。例如,對於10號線,這樣做:

cat "./Desktop/data.txt"| cut -f 1 -d ":" | sed -n 10p 
  • -n告訴sed不打印默認
  • 10便士告訴sed當它到達第10行線,它應打印。

如果您需要根據包含特定值的行選擇一行,那麼我會使用grep。如果數值與您正在切割的列不同,請確保在切割之前使用grep。

注意:原始帖子說回聲「./Desktop/data.txt」,我假設這應該是貓,而不是回聲。

2

這是AWK任務理想:

awk -F: 'NR == 2 {print $2}' "./Desktop/data.txt" 
  • -F:設置字段分隔符來:
  • NR == 2被圖案意爲 「記錄(行)數等於2」
  • {print $2}是對模式匹配執行的動作,意思是「打印第二字段」