0

I am trying to delete a line in a file by a certain keyword entered. The whole file content is then automatically displayed without the word entered (success). However, the file itself is still containing the word which should've been deleted.

This is the content of my file smilies.txt

:) smile
:( sad
;) wink
:D laughing
;( crying
:O surprise
:P tongue
:* kiss
:X nowords
:s confuse

This is my script:

echo 'Enter a smiley or its description you want to delete: '
read delsmiley
sed /"$delsmiley"/d smilies.txt
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
  • What is your question? – Ian Hazzard Nov 29 '14 at 02:07
  • sed commands are written as `sed "/x/d"` not `sed /"x"/d`. Given your posted file what would you expect to happen if someone entered "o"? What about ".*"? What about ":*"? What about "/"? – Ed Morton Nov 29 '14 at 06:08
  • Possible duplicate of [sed edit the file in place](http://stackoverflow.com/questions/12696125/sed-edit-the-file-in-place) – Benjamin W. Mar 06 '16 at 22:42

2 Answers2

2

You cannot use sed for this as sed ONLY operates on regular expressions and you need your file to be treated as fields of strings or you will have unsolvable (with sed) undesirable behavior problems given various user input (e.g. try your sed command with delsmiley set to /, :*, and o).

Use awk instead:

awk -v d="$delsmiley" '($1 != d) && ($2 != d)' smilies.txt > tmp &&
mv tmp smilies.txt

Gnu awk has a -i inplace option of you care about not explicitly specifying the tmp file name.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
1

Use -i (--in-place) option to edit the file in place:

sed -i /"$delsmiley"/d smilies.txt

-i option can be used with suffix; original file will be backuped.

sed -i.bak /"$delsmiley"/d smilies.txt

UPDATE

As Ed Morton, for some input above command will cause error. To avoid that you need to use other command that interpret input string as is. For example using grep -v with -F option:

grep -Fv "$delsmiley" smilies.txt > $$.tmp && mv $$.tmp smilies.txt
falsetru
  • 357,413
  • 63
  • 732
  • 636