在bash中读取文件时忽略第一行/列标题

Jai*_*Jai 8 bash sed

我试图从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
Run Code Online (Sandbox Code Playgroud)

但sed命令似乎不起作用.保持所有内容与header.I尝试添加双引号到1d和$ filename但不起作用.

这是我的示例输入文件内容

AccountId ProductId Product
300100051205280,300100051161910,content1
300100051199355,300100051161876,content2
Run Code Online (Sandbox Code Playgroud)

我正在使用Editra编辑器来创建我的bash脚本.任何人都可以帮助我为什么这不起作用.谢谢你提前帮助.

che*_*ner 18

read在复合命令中使用额外的内容.这比使用单独的进程跳过第一行更有效,并防止while循环在子shell中运行(如果您尝试在循环体中设置任何变量,这可能很重要).

{
    read
    while IFS=, read -r accountId ProductId Product
    do 
        echo "Account $accountId has productId $ProductId and product $Product"
    done
} < $filename
Run Code Online (Sandbox Code Playgroud)

-

原始尝试的问题在于您为while循环提供了两个输入源(通过管道sed,并通过输入减少).删除输入重定向将解决这个问题.

sed 1d $filename | while IFS=, read -r accountId ProductId Product
do 
    echo "Account $accountId has productId $ProductId and product $Product"
done
Run Code Online (Sandbox Code Playgroud)

  • 以及`while read ... done &lt;&lt;(tail -n +2 file)`呢? (2认同)

小智 7

其他答案在技术上更加精明,但我有一个简单的技巧,只要标题的第一个标题不改变,效果就很好。

while IFS=, read -r accountId ProductId Product
do 
  # If accountId matches Header line value, continue
  if [[ $accountId == "AccountId" ]]; then
     continue
  fi
  #Do your other things, assume all values are real
done < $filename
Run Code Online (Sandbox Code Playgroud)