16

I'm making an appointment tracking script in Bourne Shell and need to delete an appointment from the text file. How do I delete a line from a file leaving no white space if I have the line number? The file looks like this:

1:19:2013:Saturday:16.00:20.30:Poker  
1:24:2013:Thursday:11.00:11.45:Project meeting  
1:24:2013:Thursday:14.00:15.10:CSS Meeting
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
user1731199
  • 237
  • 1
  • 2
  • 10

3 Answers3

38

To delete line 5, do:

sed -i '5d' file.txt

For a variable line number:

sed -i "${line}d" file.txt

If the -i option isn't available in your flavor of sed, you can emulate it with a temp file:

sed "${line}d" file.txt > file.tmp && mv file.tmp file.txt
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 5
    On MacOS X -i requires a parameter for a backup file extension. You can omit it with a empty string to get the same behaviour as desired: `sed -i "" '5d' file.txt` – jmhindle Jun 02 '17 at 19:19
  • On my system, when processing large files, `sed` appears an order of magnitude slower than a simple combination of `head` and `tail`: here's an example of the faster way without in-place mode: `delete-line() { local filename="$1"; local lineNum="$2"; head -n $((lineNum-1)) "$filename"; tail +$((lineNum+1)) "$filename"; }` – Ruslan Aug 16 '20 at 08:12
4

To delete by appointement (line) number:

sed -i '3d' input

To delete by name:

sed -i '/:Poker/d' input

If the in-place (-i) option does not work on your system the you can do:

sed '/:Poker/d' input > input.tmp && mv input.tmp input
perreal
  • 94,503
  • 21
  • 155
  • 181
  • POSIX sed does not support sed -i. Since we are using Bourne here, there is a possibility this is not Linux. It won't work in Solaris /usr/bin/sed for example. – jim mcnamara Mar 14 '13 at 02:51
0

Here's a quickie using awk:

lineToDelete=$1
awk "NR != $lineToDelete"
danfuzz
  • 4,253
  • 24
  • 34
  • This doesn't delete the line from the file. It prints the file to STDOUT, except this line. – mivk Jun 05 '15 at 08:55