[英]Ignoring First line/Column header while reading a file in bash
我試圖從bash中的源txt文件中讀取,我想忽略第一行是列。在搜索一個解決方案后,使用“sed”和我的while循環如下:
#!/bin/bash
filename="source2.txt"
#fp=`sed 1d source2.txt`
#echo $fp
sed 1d $filename | while IFS=, read -r accountId ProductId Product
do
echo "Account $accountId has productId $ProductId and product $Product"
done < $filename
但sed命令似乎不起作用。保持所有內容與header.I嘗試添加雙引號到1d和$ filename但不起作用。
這是我的示例輸入文件內容
AccountId ProductId Product
300100051205280,300100051161910,content1
300100051199355,300100051161876,content2
我正在使用Editra編輯器來創建我的bash腳本。任何人都可以幫助我為什么這不起作用。謝謝你提前幫助。
在復合命令中使用額外的read
。 這比使用單獨的進程跳過第一行更有效,並防止while循環在子shell中運行(如果您嘗試在循環體中設置任何變量,這可能很重要)。
{
read
while IFS=, read -r accountId ProductId Product
do
echo "Account $accountId has productId $ProductId and product $Product"
done
} < $filename
-
您最初嘗試的問題是您為while循環提供了兩個輸入源(通過sed
的管道,並通過輸入減少)。 刪除輸入重定向將解決這個問題。
sed 1d $filename | while IFS=, read -r accountId ProductId Product
do
echo "Account $accountId has productId $ProductId and product $Product"
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.