13

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?

4
  • 2
    In a word - anchors Commented Jul 23, 2017 at 18:36
  • i did not get what you are asking ?
    – Rak kundra
    Commented Jul 23, 2017 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
    Commented Jul 23, 2017 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
    Commented Jul 24, 2017 at 4:37

1 Answer 1

27

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
1
  • Yep i got my answer thank you :) . I am trying to delete the whole line here.
    – Rak kundra
    Commented Jul 23, 2017 at 18:42

You must log in to answer this question.

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