3

I have a file that contains information as so:

20    BaDDOg
31    baddog
42    badCAT
43    goodDoG
44    GOODcAT

and I want to delete all lines that contain the word dog. This is my desired output:

42    badCAT
44    GOODcAT

However, the case of dog is insensitive.

I thought I could use a sed command: sed -e "/dog/id" file.txt , but I can't seem to get this to work. Does it have something to do with me working on an OSX? Is there any other method I could use?

0

3 Answers 3

11

Try grep:

grep -iv dog inputfile

-i to ignore case and -v to invert the matches.

If you want to use sed you can do:

sed '/[dD][oO][gG]/d' inputfile

GNU sed extends pattern matching with the I modifier, which should make the match case insensitive but this does not work in all flavors of sed. For me, this works:

sed '/dog/Id' inputfile

but it won't work on OS X.

1
  • Perfect. The grep solution was what I was looking for. My version of sed is picky. Commented Feb 5, 2016 at 19:31
1

The sed version of OSX is not GNU compliant; it totally miss the i flag as you can see in the man page:

The value of flags in the substitute function is zero or more of the following:
   N       Make the substitution only for the N'th occurrence of the regular expression in
           the pattern space.
   g       Make the substitution for all non-overlapping matches of the regular expression,
           not just the first one.
   p       Write the pattern space to standard output if a replacement was made.  If the
           replacement string is identical to that which it replaces, it is still considered
           to have been a replacement.
   w file  Append the pattern space to file if a replacement was made.  If the replacement
           string is identical to that which it replaces, it is still considered to have
           been a replacement.

You could install gsed using brew with the command

brew install gnu-sed

and then you can use sed with the case-insensitive flag like this:

gsed '/dog/Id' inputfile
0

Since OSX appears to have ed, based on https://ss64.com/osx/, you could ask it to delete any lines that match "dog". Unfortunately, you have to do the case-sensitivity yourself:

ed -s file.txt <<< $'1,$g/[dD][oO][gG]/d\nw\nq'

The command is given in a here-string, and breaks down to this sequence:

  • in the address range 1,$ (the whole file)
  • g -- globally apply the subsequent command against lines that match the upcoming regular expression
  • /[dD][oO][gG]/ -- match "dog", case-insensitively
  • d -- the command to apply is "delete"
  • w -- write the updated file to disk
  • q -- quit ed

You must log in to answer this question.

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