16

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
k-man
  • 1,121
  • 5
  • 17
  • 26
  • possible duplicate of [Bash - remove the last line from a file](http://stackoverflow.com/questions/4881930/bash-remove-the-last-line-from-a-file) – martin clayton Nov 22 '11 at 23:07

7 Answers7

17

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

Russell Dias
  • 70,980
  • 5
  • 54
  • 71
14

Here you go ! delete first line (also BSD/MacOS compatible)

sed '1,1d' file1  >> file1.out

delete last row/line

sed '$d' file2  >> file2.out 
sorin
  • 161,544
  • 178
  • 535
  • 806
name_doesnt_matters
  • 789
  • 2
  • 12
  • 34
5

You can use the --in-place (-i) switch:

sed -i '$d' filename

Source: man sed

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
5

If your sed supports in-place editing, it's sed -e '1d' -e '$d' -i filename.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
3

Because nobody gives it any love:

ed filename <<'END'
1d
$d
w
q
END
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1

Giving this answer since sed is not tagged.

head -`wc -l test2.cc | awk '{print ($1-1)}'` test2.cc
Vijay
  • 65,327
  • 90
  • 227
  • 319
  • This is not compatible with BSD version of head (MacOS) – sorin Aug 23 '18 at 14:01
  • And reading the entire file twice just to get the argument to pass to `head` is ... wacky. The entire thing could be done in just Awk with a single pass. – tripleee Aug 24 '18 at 08:20
0

Try cat file1 | sed "1,1d; $d" > file2

luis.espinal
  • 10,331
  • 6
  • 39
  • 55