Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete first and last line or record from file using sed

Tags:

sed

awk

I want to delete first and last line from the file

file1 code :

H|ACCT|XEC|1|TEMP|20130215035845|

849002|48|1208004|1

849007|28|1208004|1

T|2

After delete the output should be

849002|48|1208004|1

849007|28|1208004|1

I have tried below method but has to run it 2 times, I want one liner solution to remove both in one go!

sed '1,1d' file1.txt  >> file1.out
sed '$d' file1.out  >> file2

Please suggest one liner code....

like image 532
Rakesh Avatar asked Feb 16 '13 18:02

Rakesh


People also ask

How do you remove the first and last line of a file in Unix?

sed -i '$ d' filename . The -i flag edits file in place. This deletes the last line. To delete the first line, use sed -i '1,1d' filename .

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.

Can we delete content in a file by using sed command?

There is no available to delete all contents of the file. How to delete all contents of the file using sed command.

How do I remove the last line of a text file in Unix?

It is a sed command. d is the command for deleting a line, while $ means "the last line in the file". When specifying a location (called "range" in sed lingo) before a command, that command is only applied to the specified location. So, this command explicitly says "in the range of the last line in a file, delete it".


2 Answers

You could use ;

sed '1d; $d' file
like image 58
darque Avatar answered Sep 27 '22 22:09

darque


Use Command Separator

In sed, you can separate commands using a semicolon. For example:

sed '1d; $d' /path/to/file
like image 23
Todd A. Jacobs Avatar answered Sep 28 '22 00:09

Todd A. Jacobs