在Shell脚本中反转IP地址。

huangapple go评论55阅读模式
英文:

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 &quot;$ip&quot; | { IFS=. read q1 q2 q3 q4; echo &quot;$q4.$q3.$q2.$q1&quot;; })

...or, a little more efficiently (but a little less tersely):

IFS=. read q1 q2 q3 q4 &lt;&lt;EOF
$ip
EOF
reversed=&quot;$q4.$q3.$q2.$q1&quot;

答案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=&quot;$1&quot;
reversed=$(echo &quot;$ip&quot; | awk -F &#39;.&#39; &#39;{print $4 &quot;.&quot; $3 &quot;.&quot; $2 &quot;.&quot; $1}&#39;)
echo &quot;$reversed&quot;

答案3

得分: -2

$ echo '23.45.67.89' | 
>     mawk '$!NF = sprintf((_ = "%s.%s") "." _,
>                         $(_ = NF), $--_, $--_, $--_)' FS='[.]'
89.67.45.23
英文:
$ echo &#39;23.45.67.89&#39; | 
&gt;     mawk &#39;$!NF = sprintf((_ = &quot;%s.%s&quot;) &quot;.&quot; _,
&gt;                         $(_ = NF), $--_, $--_, $--_)&#39; FS=&#39;[.]&#39;
89.67.45.23

huangapple
  • 本文由 发表于 2023年2月16日 07:14:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75466298.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定