-1

I am writing a bash shell script, and in it I am trying to delete lines from a text file between 2 markers

START
...
...
END

Do eliminate this I have tried a few things, and every time it leave my text file blank.

sed '/START/,/END/d' myfile.txt > myfile.txt

sed '/START/d' myfile.txt > myfile.txt

As long as I have a sed command in my code, my entire file gets erased and not just the section I am looking to erase.

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
Ziggy
  • 99
  • 1
  • 1
  • 6
  • It is a duplicate, but I could not for the life of me find that question when I was searching because I wasn't searching for the right keywords. But its all fixed now. Thank you – Ziggy Aug 15 '14 at 14:40
  • The duplicate stated isn't a duplicate, the problem op is having is it overwriting after the command(which im almost usre is also a dup) –  Aug 15 '14 at 14:59

3 Answers3

4

You are redirecting stdout to the same file as stdin. When you do this, your redirection is interpreted buy the shell and it opens a new file for write with that name. Your existing file is overwritten by the newly created blank file. You will need to redirect the output to a different file or you can edit the file by using the -i option to sed.

unxnut
  • 8,509
  • 3
  • 27
  • 41
  • I did this before and it didn't work. But now that I have changed the output file it works perfectly. I could not get the `-i` flag to work at all. I would get an error at that stated that the first letter of the filename was an incorrect command. Anyway it is working now, thanks for the advice. – Ziggy Aug 15 '14 at 14:31
1

You can't redirect to a file that you are reading. That will delete your file's contents, as you've noticed.

Instead, either redirect to a different file, or edit in place:

sed -i ... myfile.txt
chrisaycock
  • 36,470
  • 14
  • 88
  • 125
0

A way in awk.

awk '/START/{x=1}/END/{x=0}!x{print > ARGV[1]}' myfile.txt

Portable

awk '/START/{x=1}/END/{x=0}!x{print > "myfile.txt"}' myfile.txt