Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting the first two lines of a file using BASH or awk or sed or whatever

Tags:

bash

sed

awk

lines

I'm trying to delete the first two lines of a file by just not printing it to another file. I'm not looking for something fancy. Here's my (failed) attempt at awk:

awk '{ (NR > 2) {print} }' myfile

That throws out the following error:

awk: { NR > 2 {print} }
awk:          ^ syntax error

Example:

contents of 'myfile':

blah
blahsdfsj
1 
2
3
4

What I want the result to be:

1
2
3
4
like image 524
Amit Avatar asked Jan 13 '12 21:01

Amit


People also ask

How do you remove the first line in awk?

The following `awk` command uses the '-F' option and NR and NF to print the book names after skipping the first book. The '-F' option is used to separate the content of the file base on \t. NR is used to skip the first line, and NF is used to print the first column only.

How do you delete a line in a file with sed?

To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.

How do I remove the first line of a text file in Linux?

sed is a common text processing utility in the Linux command-line. Removing the first line from an input file using the sed command is pretty straightforward. The sed command in the example above isn't hard to understand. The parameter '1d' tells the sed command to apply the 'd' (delete) action on line number '1'.


4 Answers

Use tail:

tail -n+3 file

from the man page:

   -n, --lines=K
          output the last K lines, instead of the last 10; or use  -n  +K
          to output lines starting with the Kth
like image 128
RobS Avatar answered Oct 22 '22 12:10

RobS


How about:

tail +3 file

OR

awk 'NR>2' file

OR

sed '1,2d' file
like image 20
anubhava Avatar answered Oct 22 '22 12:10

anubhava


You're nearly there. Try this instead:

awk 'NR > 2 { print }' myfile

awk is rule based, and the rule appears bare (i.e., without braces) before the block it woud execute if it passes.

Also as Jaypal has pointed out, in awk if all you want to do is print the line that matches the rules you can even omit the action, thus simplifying the command to:

awk 'NR > 2' myfile
like image 29
Chris J Avatar answered Oct 22 '22 13:10

Chris J


awk is based on pattern{action} statements. In your case, the pattern is NR>2 and the action you want to perform is print. This action is also the default action of awk.

So even though

awk 'NR>2{print}' filename

would work fine, you can shorten it to

awk 'NR>2' filename.

like image 39
jaypal singh Avatar answered Oct 22 '22 13:10

jaypal singh