Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash working code to delete first or last line from file

Tags:

bash

line

I saw the sed examples, but no matter how I write that it won't delete my first line. Actually, I did more tests and it won't delete my first line either, so for sure I'm doing something wrong:

sed '1d' filename

or for last line

sed '$d' file name

I want the changes to take place in the same file, and don't want another output file. So please, what's the correct way to remove the last line in my file?

like image 434
k-man Avatar asked Nov 22 '11 22:11

k-man


People also ask

How do you delete a line in a Bash script?

:g/^#/d - Remove all comments from a Bash script. The pattern ^# means each line beginning with # . :g/^$/d - Remove all blank lines. The pattern ^$ matches all empty lines.

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

txt (if it ends with EOF , or \n and then EOF ), the number of lines in new_file. txt may be the same (as file. txt ) after this command (this happens when there is no \n ) - in any case, the contents of the last line is deleted.

How do you remove the first line of a file in Unix shell script?

Using the tail Command Usually, we use the “tail -n x file” command to get the last x lines from an input file. If we prepend a “+” sign to the “x“, the “tail -n +x file” command will print starting with the xth line until the end of the file.

How do you delete a specific line in a file Linux?

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.


1 Answers

sed -i '$ d' filename. The -i flag edits file in place.

like image 155
Russell Dias Avatar answered Sep 21 '22 13:09

Russell Dias