0

How to remove the word if one of the characters in the word contains "m" or "M"?

I tried this, but it doesn't work:

 echo 6.5G 66.5m | sed -e 's/[m][M]//g'
3

Your sed command is

s/[m][M]//g

This will remove only the string mM from its input, because you've asked to match

  • anything in the set m, followed by
  • anything in the set M.

You probably meant to write [Mm] instead. You can get the same effect by adding the /i option to the s command, though:

s/m//ig

Now this will remove all upper- or lower-case ms:

$ echo 6.5G 66.5m | sed -e s/m//ig
6.5G 66.5

Your question asks how to remove entire words containing this letter. For that, we need to match any non-space characters before or after. [^ ] matches a non-space character, and [^ ]* matches zero or more non-space characters, so we want

s/[^ ]*m[^ ]*//ig

Testing this:

$ echo 6.5G 66.5m | sed -e 's/[^ ]*m[^ ]*//ig'
6.5G 

and

$ echo Five Merry Women went fishing | sed -e 's/[^ ]*m[^ ]*//ig'
Five   went fishing
0
$ echo 6.5G 66.5m | sed -e 's/[[:space:]].*[mM]//g'
6.5G

Note that the "m" and "M" form one pattern - your (non-working) version looks for an "m" followed by an "M".

  • except that the OP said "How to remove the word", not just the letter – Jeff Schaller Dec 15 '16 at 11:55
  • Uh, I missed that - discounted numbers from being in words. Updated, thanks! – John N Dec 15 '16 at 11:59
  • what about "Merry" ? – Jeff Schaller Dec 15 '16 at 12:01
  • I was only considering the OP's input. Not an excuse, though - slack on my part. A less naive solution would catch characters after the match, but before the next whitespace. I'd update my answer but there's a better answer provided (and I've voted for it). – John N Dec 15 '16 at 12:10
-1

If you want to remove you can try this

[root@connect ~]# echo 6.5M 66.5m | sed -e 's/m//g' | sed -e 's/M//g'
6.5 66.5
  • 1
    except that the OP said "How to remove the word", not just the letter – Jeff Schaller Dec 15 '16 at 11:55
  • @JeffSchaller made changes – Mongrel Dec 16 '16 at 10:36
-2

Try This it will Delete The line containg 'm' or 'M'

echo 6.5G 66.5m | sed "/[mM]/d"
  • 1
    except that the OP said "How to remove the word" – Jeff Schaller Dec 15 '16 at 11:54

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.