0

I'm trying to write a bash function to delete a garbage string (including the quotation marks and parentheses) from a text file and resave the file with the same filename.

I got it to work when I save it as a new file...

function fixfile()
{
sed 's/(\"garbagestringhere\")//g' /Users/peter/.emacs.d/recent-addresses > /Users/peter/.emacs.d/recent-addresses-fixed;
}

...but when I save it with the same filename as before, it wipes the file:

function fixfile()
{
sed 's/(\"garbagestringhere\")//g' /Users/peter/.emacs.d/recent-addresses > /Users/peter/.emacs.d/recent-addresses;
}

How do I fix this?

incandescentman
  • 6,168
  • 3
  • 46
  • 86

2 Answers2

2

For GNU sed man sed will reveal the -i option:

-i[SUFFIX], --in-place[=SUFFIX]

          edit files in place (makes backup if SUFFIX supplied)

If you are on OSx (or BSD) you can employ (see this reference answer)

sed -i '' 's/whatever//g' file
//    ^ note the space
Community
  • 1
  • 1
Pankrates
  • 3,074
  • 1
  • 22
  • 28
  • `function fixfile() { sed -i 's/(\"garbagestringhere\")//g' /Users/peter/.emacs.d/recent-addresses > /Users/peter/.emacs.d/recent-addresses; }` gives me `sed: 1: "/Users/peter/.emacs.d/rec ...": invalid command code j` – incandescentman Jun 10 '14 at 18:59
  • Do not use the output redirect `>` anymore. Just use `sed -i 'expr' INPUT_FILE` – Pankrates Jun 10 '14 at 19:01
  • `sed -i 's/(\"garbagestringhere\")//g' /Users/peter/.emacs.d/recent-addresses` still gives me `sed: 1: "/Users/peter/.emacs.d/rec ...": invalid command code j`` – incandescentman Jun 10 '14 at 19:05
  • What OS and sed version are you running? Try `sed --version`. You are probably on OSx right? – Pankrates Jun 10 '14 at 19:10
  • Yes, I'm on OSX. `$ sed --version sed: illegal option -- - usage: sed script [-Ealn] [-i extension] [file ...] sed [-Ealn] [-i extension] [-e script] ... [-f script_file] ... [file ...]` – incandescentman Jun 10 '14 at 19:11
1

Even if in your particular case I suggest the use of sed -i,
in a more general approach you can consider the use of sponge from moreutils.

sed '...' file | grep '...' | awk '...' | sponge file

Sponge reads standard input and writes it out to the specified file. Unlike a shell redirect, sponge soaks up all its input before opening the output file. This allows constricting pipelines that read from and write to the same file. If no output file is specified, sponge outputs to stdout

(Git from here, or from here...)

Alternatively you can use a temporary file that you delete before you exit from your function. Temporary file with a random (or pseudorandom) namefile.

Community
  • 1
  • 1
Hastur
  • 2,470
  • 27
  • 36