Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

alma a fa
alatt
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

2 Answers 2

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.