3

How would I delete all lines (from a text file) which contain only two dots, with random data between the dots. Some lines have three or more dots, and I need those to remain in the file. I would like to use sed.

Example Dirty File:

.dirty.dig
.please.dont.delete.me
.delete.me
.dont.delete.me.ether
.nnoooo.not.meee
.needto.delete

Desired Output:

.please.dont.delete.me
.dont.delete.me.ether
.nnoooo.not.meee
Wolfie
  • 21,886
  • 7
  • 23
  • 50

5 Answers5

2

Would be simpler to use awk here

$ awk -F. 'NF!=3' ip.txt
.please.dont.delete.me
.dont.delete.me.ether
.nnoooo.not.meee
  • -F. use . as delimiter
  • NF!=3 print all lines where number of input fields is not equal to 3
    • this will retain lines like abc.xyz
    • to retain only lines with more than 2 dots, use awk -F. 'NF>3' ip.txt
Sundeep
  • 19,273
  • 2
  • 19
  • 42
  • I apologize, my data had some hyphens at the ends of the lines which were interfearing, this actually works incredibly well. – derpderpalert Apr 16 '17 at 01:11
1
sed '/^[^.]*\.[^.]*\.[^.]*$/d' file

Output:

.please.dont.delete.me
.dont.delete.me.ether
.nnoooo.not.meee

See: The Stack Overflow Regular Expressions FAQ

Community
  • 1
  • 1
Cyrus
  • 69,405
  • 13
  • 65
  • 117
1

sed is for making substitutions, to just Globally search for a Regular Expression and Print the result there's a whole other tool designed just for that purpose and even named after it - grep.

grep -v '^[^.]*\.[^.]*\.[^.]*$' file

or with GNU grep for EREs:

$ grep -Ev '^[^.]*(\.[^.]*){2}$' file
.please.dont.delete.me
.dont.delete.me.ether
.nnoooo.not.meee
Ed Morton
  • 157,421
  • 15
  • 62
  • 152
  • 1
    I apologize, my data had some hyphens at the ends of the lines which were interfearing, this actually works incredibly well. – derpderpalert Apr 16 '17 at 01:12
0

I don't have a sed handy to double-check, but

/^[^.]*\.[^.]*\.[^.]*$/d

should match and delete all lines that have two dots with non-dot strings before and between them.

Ulrich Schwarz
  • 7,355
  • 1
  • 30
  • 43
0

This might work for you (GNU sed):

sed 's/\./&/3;t;s//&/2;T;d' file

If there are 3 or more . print. If there are 2 . delete. Otherwise print.

Another way:

sed -r '/^([^.]*\.[^.]*){2}$/d' file
potong
  • 47,186
  • 6
  • 43
  • 72