Pages

Showing posts with label head. Show all posts
Showing posts with label head. Show all posts

Wednesday, October 17, 2012

Delete last line from a file using Linux command or Shell script

Q. Delete or remove last line from a file.


This can be achieved  with SED command.

sed -i '$d' filename

Let me explain this command. SED is a stream editor which is useful for editing stream of characters. here -i option say's to insert the data in to the original file, ie modify original file. $ indicates last line and d for deleting that line and update to the file.

There are other methods to delete last lines

head -n -1 file1 > file2;mv file2 file1

Here I used head command to list all the lines but not the last line, redirected the output of this to a new file then moved file1 to file2.




Saturday, August 18, 2012

Move all file description(first 5 lines) of a file to file

Q. I have a requirement to move all my shell script meta data such as interpreter, Author, date, purpose etc which occupies my first 5 lines.

With head

head -n5 *.sh > file.txt

With SED


sed -n '1,4 p' xyz.txt 

or

sed '5,$ d' xyz.txt

you can keep this one in for loop and execute sed command get your file content to other file.