8

I have a txt file

123
456
789
456
123456

I want to delete specific characters from the file i.e (123). I tried with

$ sed -i '/123/d' dummy.sh
$ vi dumm.txt
456
789
456

In the below command when I run both the words (123 and 123456) are getting deleted but I need to delete only 123 from the file

$ sed -i 's/123//g' dummy.sh
$ vi dumm.txt
456
789
456
456

when I run the below command the 123 is getting replaced with null.

Can anyone say how to delete a whole line if it contains only specific number?

  • 2
    In a word - anchors – steeldriver Jul 23 '17 at 18:36
  • i did not get what you are asking ? – Rak kundra Jul 23 '17 at 18:38
  • 1
    Note that while it is perfectly ok to use sed for this task, grep is the tool which was created specifically to display or hide lines of input matching the pattern. In this case the following grep command would do the same: grep -E -v '^123$' dumm.txt – Gnudiff Jul 23 '17 at 22:56
  • 4
    @Gnudiff I don't see any advantage of grep if you use is like that. But it can be superior for some tasks due to it's options: grep -xv 123 – Philippos Jul 24 '17 at 4:37
18

It is unclear if you are trying to delete whole line with 123 or replace it with empty line. Anyhow, just add anchors of beginning ^ and end $ of line to your pattern:

sed -i '/^123$/d' dummy.sh      #delete whole line
sed -i 's/^123$//' dummy.sh     #replace with empty line
  • Yep i got my answer thank you :) . I am trying to delete the whole line here. – Rak kundra Jul 23 '17 at 18:42

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.