Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

sed

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 :

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

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.

like image 343
Jai Avatar asked Aug 10 '15 03:08

Jai


People also ask

How do I skip the first line in bash?

Using head to get the first lines of a stream, and tail to get the last lines in a stream is intuitive. But if you need to skip the first few lines of a stream, then you use tail “-n +k” syntax. And to skip the last lines of a stream head “-n -k” syntax.

How do you skip the first line of a file in shell?

The first line of a file can be skipped by using various Linux commands. As shown in this tutorial, there are different ways to skip the first line of a file by using the `awk` command. Noteably, the NR variable of the `awk` command can be used to skip the first line of any file.

What does $() mean in bash?

Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).


1 Answers

Use an extra read inside 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
    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.

sed 1d $filename | while IFS=, read -r accountId ProductId Product
do 
    echo "Account $accountId has productId $ProductId and product $Product"
done
like image 137
chepner Avatar answered Oct 23 '22 12:10

chepner