echo "./Desktop/data.txt"| cut -f 1 -d ":"
以上線切割線的特定字段分隔符「:」shell腳本切斷特定行和特定領域
但我怎麼能砍特定行和特定領域與分隔符「:」如果我的文件由多條線組成?
echo "./Desktop/data.txt"| cut -f 1 -d ":"
以上線切割線的特定字段分隔符「:」shell腳本切斷特定行和特定領域
但我怎麼能砍特定行和特定領域與分隔符「:」如果我的文件由多條線組成?
我將模擬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可以通過尋找與/:/
線來完成。
您應該將其與-n
和p
結合使用。
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}'
如果您正在根據行號選擇一行,那麼您可以使用sed。例如,對於10號線,這樣做:
cat "./Desktop/data.txt"| cut -f 1 -d ":" | sed -n 10p
如果您需要根據包含特定值的行選擇一行,那麼我會使用grep。如果數值與您正在切割的列不同,請確保在切割之前使用grep。
注意:原始帖子說回聲「./Desktop/data.txt」,我假設這應該是貓,而不是回聲。
這是AWK任務理想:
awk -F: 'NR == 2 {print $2}' "./Desktop/data.txt"
-F:
設置字段分隔符來:
NR == 2
被圖案意爲 「記錄(行)數等於2」{print $2}
是對模式匹配執行的動作,意思是「打印第二字段」