3

I have a file with one word/character for each line. Example:

a
abandonado
esta
estabelecimento
o
onibus
c
casa
police

I need remove lines with specific pattern (ex. pattern "esta"). I tried with awk

cat file | awk '!/^esta/' 

but this solution remove the all lines with the pattern "esta" and "estabelecimento" too. I need only remove the line with the specific pattern "esta" not line with "estabelecimento".

The same problem occurs with the lines with the patterns "o" and "a". The command removes all lines with start with this pattern.

Inian
  • 62,560
  • 7
  • 92
  • 110
vivas
  • 33
  • 5
  • 1
    See: [The Stack Overflow Regular Expressions FAQ](http://stackoverflow.com/a/22944075/3776858) – Cyrus Dec 30 '16 at 18:49

4 Answers4

9

simple using grep:

grep -v -w esta file
  • -w option matches "word only" / "exact word": exactly what you need
  • -v option reverses matches: only prints the lines which don't match
Jean-François Fabre
  • 126,787
  • 22
  • 103
  • 165
4

Your idea is right, ^ matches the start of pattern, finish it by matching $ for pattern end, so that the whole-word is matched as it is

awk '!/^esta$/' file
a
bandonado
estabelecimento
o
onibus
c
casa
police
Inian
  • 62,560
  • 7
  • 92
  • 110
3

Since your file consists of lines with just one column you can check if a column matches a string.

This removes the need for anchors ^, $:

$ awk '$1 != "esta" {print}' file
  a
  abandonado
  estabelecimento
  o
  onibus
  c
  casa
  police
Zlemini
  • 3,835
  • 2
  • 15
  • 19
2

You can also do this with sed as per this question:

$ cat test.txt
a
abandonado
esta
estabelecimento
o
onibus
c
casa
police

.

$ sed '/^esta$/d' test.txt
a
abandonado
estabelecimento
o
onibus
c
casa
police

grep is simpler but sed can give you more flexibility, depends on your use case & comfort level with each.

Community
  • 1
  • 1
user5359531
  • 2,546
  • 4
  • 19
  • 46
  • 1
    There is no need to use cat, sed itself is capable to read the file and do the operations, it is often called UUOC(Useless use of cat). – RavinderSingh13 Dec 30 '16 at 18:25