开发者

How to remove caracters like (), ' * [] form a grep results with grep, awk or sed?

For example if I made a file with grep that give me a next result:

16 Jan 07:18:42 (name1), xx.210.49.xx),
16 Jan 07:19:14 (name2), xx.210.xx.24),
16 Jan 07:19:17 (name3), xx.140.xxx.79),
16 Jan 07:19:44 (name4), xx.210.49.xx),
16 Jan 07:19:56 (name5), xx.140.xxx.79),

,then how to sed awk or grep to remove all except date name and IP to look like this:

16 Jan 07:18:42 name1 xx.210.49.xx
16 Jan 07:19:14 name2 xx.210.xx.24
16 Jan 07:19:17 name3 xx.140.xxx.79
16 Jan 07:19:44 name4 xx.210.49.xx
16 Jan 07:19:56 name5 x开发者_JS百科x.140.xxx.79

My grep command look like this:

grep 'double' $DAEMON | awk -F" " '{print $2" "$1" "$3" "$8" "$10}'  > $DBLOG

Thx.


If you just want to strip certain characters, you might want to look at the tr command with the -d option:

$ echo "16 Jan 07:18:42 (name1), xx.210.49.xx)," | tr -d "(),*'[]"
16 Jan 07:18:42 name1 xx.210.49.xx


you can do it with just one awk command. no need to use grep

awk '/double/{gsub("[(),]","",$8); gsub("[(),]","",$10);print $2" "$1" "$3" "$8" "$10}'

or just

awk '/double/{gsub("[(),]","");print $2" "$1" "$3" "$8" "$10}'

if you need to remove [] as well, then use this pattern: gsub("[][(),]","")


Breaking down ghostdog74's answer:

awk '
    /double/ {
        gsub(/[(),\[\]]/, "")
        print $2" "$1" "$3" "$8" "$10
    }
'

/double/ tells awk to only perform the stuff in { } for lines that contain double (/double/ is a regular expression).

gsub expects the first argument to be a regular expression, the second argument to be a substitution string, and the third argument to be the variable that the substitution is being performed on. If the third argument is not specified (as in this case) it defaults to $0 which matches the entire line.

I added \[ and \] to the regular expression which should match [ and ] characters in addition to (, ) and ,.

In general whenever you find yourself combining awk, sed or grep, there is almost always a way to do what you need with just sed or just awk.


With sed

$> cat ./text | sed -r -e 's/(\(|\)\,)//g'
16 Jan 07:18:42 name1 xx.210.49.xx
16 Jan 07:19:14 name2 xx.210.xx.24
16 Jan 07:19:17 name3 xx.140.xxx.79
16 Jan 07:19:44 name4 xx.210.49.xx
16 Jan 07:19:56 name5 xx.140.xxx.79

Inb4 UselesUseOfCat: cat ./text here is similar for OP's grep output.


[jaypal@MBP-13~/temp] cat file1
16 Jan 07:18:42 (name1), xx.210.49.xx),
16 Jan 07:19:14 (name2), xx.210.xx.24),
16 Jan 07:19:17 (name3), xx.140.xxx.79),
16 Jan 07:19:44 (name4), xx.210.49.xx),
16 Jan 07:19:56 (name5), xx.140.xxx.79),

[jaypal@MBP-13~/temp] sed 's/\(.*[^(]\)(\(.*\)),\(.*\)),/\1\2\3/g' file1
16 Jan 07:18:42 name1 xx.210.49.xx
16 Jan 07:19:14 name2 xx.210.xx.24
16 Jan 07:19:17 name3 xx.140.xxx.79
16 Jan 07:19:44 name4 xx.210.49.xx
16 Jan 07:19:56 name5 xx.140.xxx.79
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜