Shivam Agrawal
Shivam Agrawal

Reputation: 2103

How to remove the header from a file only if exist in bash?

I have this sample file. I want to remove the first line (header) of this file only when it (header) exist using bash.

id name job_id
1 john 25
2 adam 45
3 paul 75

Upvotes: 2

Views: 3423

Answers (5)

Aleks-Daniel Jakimenko-A.
Aleks-Daniel Jakimenko-A.

Reputation: 10653

filename='myfile'
[[ $(head -n 1 -- "$filename") == 'id name job_id' ]] && sed -i '1d' -- "$filename"

Upvotes: 2

thefourtheye
thefourtheye

Reputation: 607

if head -1 original.txt | grep -Fxq 'id name job_id'
then tail -n+2 original.txt > newdoc.txt
fi

EDIT: Only checks first line and prints rest in a new file if the header exists. If not, the original is unchanged.

Upvotes: 1

iamauser
iamauser

Reputation: 11479

You can also use awk to do this :

awk 'NR!=1||$0!="id name job_id" {print $0}' file > newfile

Upvotes: 3

Jonathan Leffler
Jonathan Leffler

Reputation: 754190

You can do it in one operation with sed using the -i option (assuming your version of sed supports it — not all do). For example:

sed -i.bak -e '1{/^id name job_id/d;}' file

This takes line 1 of the file and applies the commands in the braces to it. The braces search for the pattern shown and delete the line. If the first line doesn't match, it isn't deleted. Other lines are left untouched.

The semicolon and backup suffix are necessary with Mac OS X sed; with GNU sed, you could omit either or both.

Upvotes: 5

Harshad
Harshad

Reputation: 101

sed '/id name job_id/d' fileName

Upvotes: -3

Related Questions