简体   繁体   English

在bash别名$ argv中自动转义IP地址

[英]Auto-escaping an IP address in bash alias $argv

I want to set up a bash alias to grep all logs in a directory automatically; 我想设置一个bash别名来自动grep目录中的所有日志; however, to make this user-friendly, I need to escape the periods and add a whitespace boundary so grep won't match too many lines. 但是,为了使此界面友好,我需要转义句点并添加空格边界,以使grep不会匹配太多行。

First I checked to be sure that I had the right syntax to escape an address... 首先,我检查以确保我使用正确的语法来转义地址...

[mpenning@sasmars daily]$ echo 1.1.1.1 | sed "s/\./\\\\./g"
1\.1\.1\.1
[mpenning@sasmars daily]$

Next I tried to escape a CLI argument... but it's not quite getting me there... 接下来,我尝试转义一个CLI参数...但是这并不能使我到达那里...

[mpenning@sasmars daily]$ alias tryme='echo `sed "s/$argv[1]/\\\\./g"`'
[mpenning@sasmars daily]$ tryme 1.1.1.1

-> Indefinite hang until I hit cntl c ->无限挂起,直到我按下cntl c

I realize that echo isn't going to search, but this was a simple test. 我意识到回声不会被搜索到,但这是一个简单的测试。

What is the simplest way to escape periods in arguments to a bash alias? 在bash别名的参数中转义句点的最简单方法是什么?

What you want is a function, and you can use bash's builtin replacement syntax: 您想要的是一个函数,您可以使用bash的内置替换语法:

$ function tryme() { echo "${1//./\.}"; }
$ tryme 1.1.1.1
1\.1\.1\.1
$ tryme "also. with ... spaces"
also\. with \.\.\. spaces

This will avoid you from forking a sed process. 这将避免您分叉sed过程。

According to §6.6 "Aliases" of the Bash Reference Manual : 根据Bash参考手册的第6.6节“别名”

There is no mechanism for using arguments in the replacement text, as in csh . 没有像csh那样在替换文本中使用参数的机制。 If arguments are needed, a shell function should be used (see Shell Functions ). 如果需要参数,则应使用shell函数(请参见Shell Functions )。

Also, sed "s/$argv[1]/\\\\\\\\./g" wouldn't really make sense anyway, if it put the argument in the sed pattern rather than in the input string. 同样, sed "s/$argv[1]/\\\\\\\\./g"如果将参数放在sed模式而不是输入字符串中,则无论如何都没有意义。

So, you would write: 因此,您将编写:

function tryme() {
    echo "$(echo "$1" | sed "s/\./\\\\./g")"
}

or, using <<< to pass in the input: 或者,使用<<<传入输入:

function tryme() {
    echo "$(sed "s/\./\\\\./g" <<<"$1")"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM