简体   繁体   中英

Bash “reverse” a string

IP 12.34.56.78

I want to find a way to echo this and display the below output

78.56.34.12

same as the output of host 12.34.56.78 but without all of the other jargon....

Maybe could just use the host and cut out all of the other stuff. Ideally would liek to avoid the host lookup.

Any ideas?

Thanks

try this one-liner:

awk -F. '{s="";for (i=NF;i>1;i--) s=s sprintf("%s.",$i);$0=s $1}1' file

with your example:

kent$  echo "12.34.56.78"|awk -F. '{s="";for (i=NF;i>1;i--) s=s sprintf("%s.",$i);$0=s $1}1'
78.56.34.12

if you have a prefix HOST or IP or whatever :

kent$  echo "FOO 12.34.56.78"|awk -F'[. ]' '{s="";for (i=NF;i>2;i--) s=s sprintf("%s.",$i);$0=$1" "s $2}1' 
FOO 78.56.34.12

我认为我的答案不能解决您的问题,Kent似乎为您提供了一种很好的方法,但是如果其他人正在寻找反转BASH字符串并在此处使用的话,这可能会很有用:

echo -n $YOUR_STRING | tac -rs [^-\n] 

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