Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to delete a word's all occurences in a text file with sed. I have this file f1:

alma a fa
nyari piros alma

and I'd like to delete all occurences of "alma". I use the following in a .sh script:

a=`sed "s/alma//g" $ file`; 
echo -e $a | cat > $file

where $file contains the name of this text file I've just written before. The problem is that sed does not take into account the linefeed and my new f1 file looks like this:

a fa alatt nyari piros.

So everything is written in a single line, however, I'd like to preserve the f1's original form with separate lines.
How could I do that?

share|improve this question
up vote 3 down vote accepted

With GNU sed, you can achieve this with a single command:

sed -i "s/alma//g" f1

-i edits the file in place.

For BSD sed, e.g. on OS X, options are different: you need sed -i '' 's/alma//g' f1.

share|improve this answer
It works! Thanks very much! – Eszter Apr 14 '13 at 9:38

You missed the quotes.

a=$(sed "s/alma//g" $file);
printf %b "$a" > $file

You should always use quotes around parameter expansion, unless you know what you are doing.

However, I think that parkydr's one-liner is more readable.

share|improve this answer
Side notes: In general, you should prefer printf to echo. There's no reason to spawn an additional process for cat - redirection is fine. $() is preferred to ` – ignis Apr 19 '13 at 18:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .