[英]Bash command rev to reverse delemiters
I am working on a shell script that converts exported Microsoft in-addr.apra.txt files to a more useful format so that i can use it in the future in other products for automation purposes. 我正在开发一个shell脚本,它将导出的Microsoft in-addr.apra.txt文件转换为更有用的格式,以便将来可以在其他产品中用于自动化目的。 No i am figuring a problem which (im not a programmer) can not solve in a simple way.
不,我正在解决一个问题(我不是程序员)无法以简单的方式解决。
Sample script 示例脚本
x=123.223.224
rev $x
gives me 给我
422.322.321
but i want to have the output as follow: 但我希望输出如下:
224.223.123
is there a easy way to do it without rev or putting each group in a variable? 没有转速或将每个组放在一个变量中,有没有一种简单的方法可以做到这一点? Or is there a sample i can use?
或者我有可以使用的样品吗? or maybe i use the wrong tools to do it?
或者我可能使用错误的工具来做到这一点?
Using awk
: 使用
awk
:
x='123.223.224'
awk 'BEGIN{FS=OFS="."} {for (i=NF; i>=2; i--) printf $i OFS; print $1}' <<< "$x"
224.223.123
Use awk
for this! 使用
awk
这个!
If your text file always contains three octets, simply use .
如果您的文本文件始终包含三个八位字节,请使用
.
as separator: 作为分隔符:
echo $x | awk -F. '{ print $3 "." $2 "." $1 }'
For more complex cases, use internal split()
: 对于更复杂的情况,请使用内部
split()
:
echo $x | awk '{
n = split($0, a, ".");
for(i = n; i > 1; i--) {
printf "%s.", a[i];
}
print a[1]; }'
In this sample split()
will split every line (which is passed as argument $0
) using delimiter .
在此示例中,
split()
将使用分隔符拆分每一行(作为参数$0
传递) .
, saves resulting array into a
and returns length of that array (which is saved to n
). ,将结果数组保存到
a
并返回该数组的长度(保存到n
)。 Note that unlike C, split()
array indexes are starting with one. 请注意,与C不同,
split()
数组索引以1开头。
Or python
: 或者
python
:
python -c "print '.'.join(reversed('$x'.split('.')))"
Here is my script. 这是我的剧本。
#!/bin/sh
value=$1
delim=$2
total_fields=$(echo "$value" | tr -cd $2 | wc -c)
let total_fields=total_fields+1
i=1
reverse_value=""
while [ $total_fields -gt 0 ]; do
cur_value=$(echo "$value" | cut -d${delim} -f${total_fields})
if [ $total_fields -ne 1 ]; then
cur_value="$cur_value${delim}"
fi
#echo "$cur_value"
reverse_value="$reverse_value$cur_value"
#echo "$i --> $reverse_value"
let total_fields=total_fields-1
done
echo "$reverse_value"
使用一些小工具。
tr '.' '\n' <<< "$x" | tac | paste -sd.
224.223.123
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.