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?


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.


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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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