英文:
Reverse an IP, in shell script
问题
我正在寻找一种更简洁、更惯用,更重要的是符合标准(POSIX)的方法,使用Unix shell中的sh
来反转IP地址。
以下是我的当前解决方案:
RevIP() {
echo "$1"|tr . "\n"|tac|tr "\n" .
# 'Split' on the dot character, reverse the list, 'join' with dot
}
示例_用法_:
$ RevIP 23.45.67.89
89.67.45.23.
问题:
- 这使用了
tac
,而它不在POSIX中。 - 输出以
.
结尾,没有换行符。虽然不是主要问题,但理想情况下应该以\n
结尾。这可以通过额外的|sed s/...
解决,但是否有更优雅的方法可以避免这样做?
英文:
I am looking for a simpler, more idiomatic and most importantly standards (POSIX) compliant way to reverse an IP address, using sh
the Unix shell.
Here's my current solution:
RevIP() {
echo "$1"|tr . "\n"|tac|tr "\n" .
# 'Split' on the dot character, reverse the list, 'join' with dot
}
Example usage:
$ RevIP 23.45.67.89
89.67.45.23.
Issues:
- this uses
tac
which is not in POSIX - the output ends in
.
and there's no newline. Not a major problem but ideally it should end in\n
instead.
This could be solved by an additional|sed s/...
at the end but is there a way to do this more elegantly so there's no need for that?
答案1
得分: 1
One doesn't need external commands for this; shell builtins suffice.
reversed=$(echo "$ip" | { IFS=. read q1 q2 q3 q4; echo "$q4.$q3.$q2.$q1"; })
...或者,稍微更高效一些(但稍微不太简洁):
IFS=. read q1 q2 q3 q4 <<EOF
$ip
EOF
reversed="$q4.$q3.$q2.$q1"
英文:
One doesn't need external commands for this; shell builtins suffice.
reversed=$(echo "$ip" | { IFS=. read q1 q2 q3 q4; echo "$q4.$q3.$q2.$q1"; })
...or, a little more efficiently (but a little less tersely):
IFS=. read q1 q2 q3 q4 <<EOF
$ip
EOF
reversed="$q4.$q3.$q2.$q1"
答案2
得分: 0
这应该是你在寻找的一个可能性
#!/bin/sh
ip="$1"
reversed=$(echo "$ip" | awk -F '.' '{print $4 "." $3 "." $2 "." $1}')
echo "$reversed"
英文:
this should be one possibility for what you're looking
#!/bin/sh
ip="$1"
reversed=$(echo "$ip" | awk -F '.' '{print $4 "." $3 "." $2 "." $1}')
echo "$reversed"
答案3
得分: -2
$ echo '23.45.67.89' |
> mawk '$!NF = sprintf((_ = "%s.%s") "." _,
> $(_ = NF), $--_, $--_, $--_)' FS='[.]'
89.67.45.23
英文:
$ echo '23.45.67.89' |
> mawk '$!NF = sprintf((_ = "%s.%s") "." _,
> $(_ = NF), $--_, $--_, $--_)' FS='[.]'
89.67.45.23
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论