I have a logfile with the following format:Jul 13 21:47:41 192.168.100.254 user from 192.168.100.101I need to remove ALL lines that contain IP's in the 192.168.x.x range but only if they appear in the 4th column. I also need to exclude 3 IP's from the 192.168.x.x range. Lets call these 192.168.125.100192.168.126.100192.168.155.240 How can I finish this command to find all the IP's in the 192.168.x.x range in the 4th column and remove all the lines except the ones that contain 192.168.125.100, 192.168.126.100, and 192.168.155.240. awk '{print $4}' file | grep '192.168' | remove all found except | > save back to original file
remove lines that contain IP range from specific column while making exclusions to range
command line;awk;sed;text formatting
Try:awk '{f=1} $4 ~ /^192.168/{f=0} $4 ~ /192.168.(125.100|126.100|155.240)/{f=1} f' fileExampleConsider this test file:$ cat fileJul 13 21:47:41 192.168.100.254 user from 192.168.100.101Jul 13 21:47:41 192.168.125.100 user from 192.168.100.101Jul 13 21:47:41 192.168.126.100 user from 192.168.100.101Jul 13 21:47:41 192.168.155.240 user from 192.168.100.101Jul 13 21:47:41 123.456.789.240 user from 192.168.100.101As I understand your rules, you want to keep all but the first line above.$ awk '{f=1} $4 ~ /^192.168/{f=0} $4 ~ /192.168.(125.100|126.100|155.240)/{f=1} f' fileJul 13 21:47:41 192.168.125.100 user from 192.168.100.101Jul 13 21:47:41 192.168.126.100 user from 192.168.100.101Jul 13 21:47:41 192.168.155.240 user from 192.168.100.101Jul 13 21:47:41 123.456.789.240 user from 192.168.100.101Multiline versionFor those who prefer their code spread over multiple lines:awk '  {    f=1  }  $4 ~ /^192.168/ {    f=0  }  $4 ~ /192.168.(125.100|126.100|155.240)/ {    f=1  }  f  ' fileHow it worksThe code uses a single variable f.  If a line should be kept, we set f=1.  Otherwise, f is set to zero.f=1To begin, assume that the line should be kept.$4 ~ /^192.168/{f=0}If $4 starts with 192.168, then mark the line as one that we should lose.$4 ~ /192.168.(125.100|126.100|155.240)/{f=1}For these three special cases, mark the line as a keeper: f=1.fThis is awk's cryptic shorthand for: if f is true (nonzero), then print the line. Additional testingAs per the comments, we will try file2:$ cat file2Jul 13 21:47:41 192.168.100.125 user from 192.168.100.101Jul 13 21:47:41 192.168.202.150 user from 192.168.100.101Jul 13 21:47:41 192.168.101.45 user from 192.168.100.101Now, let's run our command:$ awk '{f=1} $4 ~ /^192.168/{f=0} $4 ~ /192.168.(125.100|126.100|155.240)/{f=1} f' file2$ All these lines were removed as they should be.