简体   繁体   中英

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; 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.

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...

[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

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?

What you want is a function, and you can use bash's builtin replacement syntax:

$ 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.

According to §6.6 "Aliases" of the Bash Reference Manual :

There is no mechanism for using arguments in the replacement text, as in csh . If arguments are needed, a shell function should be used (see 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.

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")"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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