开发者

How to create inverse of scrubbing script in SED?

I wrote an SED script that deletes rows ("/d") that match a set of IP regular expressions. Now I want to re-read the same source file and create the inverse output - delete anything that is not in that list.

If I just throw a "!" expression, it will delete everything since they will all match the "not" condition of all the other IP list entries.

Here's the example of my regex in internal.lst:

/10\.10\.50\.0/d
/10\.100\.0\.0/d
/10\.101\.0\.0/d
/10\.101\.0\.128/d

And an example of the SED execution (in a .bat file):

for /f %%f IN ('dir /b source\*.txt') do (
  sed -f ..\internal.lst staging\%%f > scrubbed\external\%%f
  REM some inverse of above line!!!!   >scrubbed\internal\%%f
move staging\%%f scrubbed\original

    )

EDIT: To confirm that I understand bobbogo's comment, I'd do something like:

sed -f list.lst staging\in.txt > out.txt

and I'll put in the list.lst file:

/10\.100\.0\.0{p;n}
/10\.101\.0\.0{p;n}
/10\.101\.0\.128{p;n}
开发者_高级运维

is that right?


In GNU sed, the -n option suppresses the automatic printing of the pattern space, which allows you to use the p command to print select lines:

$ cat in.txt 
10.101.0.128
10.101.0.133
10.101.0.11
$ sed -n '/10\.10\.50\.0/p
/10\.100\.0\.0/p
/10\.101\.0\.0/p
/10\.101\.0\.128/p' in.txt
10.101.0.128

EDIT:

Note that this approach will produce duplicates if an input line can match with more than one expressions:

$ cat in.txt 
10.101.0.0
10.101.0.128
10.101.0.133
10.101.0.11
$ sed -n '/10\.10\.50\.0/p
/10\.100\.0\.0/p
/10\.101\.0\.0/p
/10\.101\.0\.128/p
/10\.101\.0\.[0-9]$/p' in.txt
10.101.0.0
10.101.0.0
10.101.0.128

To deal with this, you can use the p command, followed by the d command:

$ sed -n '/10\.10\.50\.0/{p; d}
/10\.100\.0\.0/{p; d}
/10\.101\.0\.0/{p; d}
/10\.101\.0\.128/{p; d}
/10\.101\.0\.[0-9]$/{p; d}' in.txt
10.101.0.0
10.101.0.128

EDIT:

As per the comment by bobbogo, you can use the n command instead of d.


You used the 'd' command. Now use the 'p' command, combined with -n flag (-n to not output not-matching rows, p to print matching ones)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜