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
  • 27,562
  • 7
  • 28
  • 55

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
  • 23,246
  • 2
  • 28
  • 103
  • 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
  • 84,225
  • 14
  • 89
  • 153
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
  • 188,023
  • 17
  • 78
  • 185
  • 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,598
  • 1
  • 36
  • 48
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
  • 55,640
  • 6
  • 51
  • 83