4

I'm working in a small bash script. I need to remove an entire line that match an exact word in only the first word of the line.

That's how the text file looks:

John is a dumb
Maria is awesome
Toni and Maria are funny

I want to remove the just the second line.

Right now, I can match the exact word "maria" but it removes the third line too:

sed -i "/\b\(maria\)\b/d" file.txt

How to specify just the first word?

Thanks!

Dani Polo
  • 403
  • 2
  • 6
  • 22

1 Answers1

6

Currently you are looking for "maria" surrounded by a word boundary (represented by \b.) Instead look for "maria" preceded by the start of line (represented by ^.) Note I've also removed unnecessary parentheses and added the /I flag, which will make the search case-insensitive. Your original wouldn't have matched "Maria".

sed -i "/^maria\b/Id" file.txt

Edit: fixed case insensitive flag to I instead of i!

miken32
  • 42,008
  • 16
  • 111
  • 154
  • It doens't work in ksh? If text has line as 'maria-d' then? doesn't work – rohansr002 Jan 30 '20 at 13:01
  • ksh is a shell. sed is a program. They aren’t really related. I addressed the sample data in the question, but I’m sure in most languages the word boundary assertion matches hyphens. – miken32 Jan 30 '20 at 14:30