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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31911179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:24:45  来源:igfitidea点击:

Ignoring First line/Column header while reading a file in bash

bashsed

提问by Jai

I am trying to read from a source txt file in bash and I want to ignore the first line which is the column.After searching around one solution was to use "sed" with my while loop like below :

我正在尝试从 bash 中的源 txt 文件中读取,我想忽略作为列的第一行。搜索周围的一个解决方案是在我的 while 循环中使用“sed”,如下所示:

#!/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

But the sed command does not seem to work.Keeps giving all the contents with header.I tried adding double quotes to 1d and also $filename but does not work.

但是 sed 命令似乎不起作用。继续提供带有标题的所有内容。我尝试向 1d 和 $filename 添加双引号,但不起作用。

Here is my sample input file content

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

AccountId ProductId Product
300100051205280,300100051161910,content1
300100051199355,300100051161876,content2

I am using Editra editor for creating my bash script.Can anyone help me why this is not working.Thanks for the help in advance.

我正在使用 Editra 编辑器来创建我的 bash 脚本。谁能帮助我为什么这不起作用。提前感谢您的帮助。

回答by chepner

Use an extra readinside a compound command. This is more efficient than using a separate process to skip the first line, and prevents the while loop from running in a subshell (which might be important if you try to set any variables in the body of the loop).

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

{
    read
    while IFS=, read -r accountId ProductId Product
    do 
        echo "Account $accountId has productId $ProductId and product $Product"
    done
} < $filename

--

——

The problem with your original attempt is that you were providing two sources of input to the while loop (via the pipe from sed, and via an input reduction). Dropping the input redirection would fix that.

您最初尝试的问题在于您为 while 循环提供了两个输入源(通过管道 fromsed和通过输入减少)。删除输入重定向可以解决这个问题。

sed 1d $filename | while IFS=, read -r accountId ProductId Product
do 
    echo "Account $accountId has productId $ProductId and product $Product"
done