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?

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

5 Comments

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
Do not use the output redirect > anymore. Just use sed -i 'expr' INPUT_FILE
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``
What OS and sed version are you running? Try sed --version. You are probably on OSx right?
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 ...]
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.