Reputation: 704
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. 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?
Upvotes: 1
Views: 383
Reputation: 247042
Using a few small tools.
tr '.' '\n' <<< "$x" | tac | paste -sd.
224.223.123
Upvotes: 0
Reputation: 5356
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"
Upvotes: 1
Reputation: 11514
Use awk
for this!
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()
:
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 .
, saves resulting array into a
and returns length of that array (which is saved to n
). Note that unlike C,
split()
array indexes are starting with one.
Or python
:
python -c "print '.'.join(reversed('$x'.split('.')))"
Upvotes: 1
Reputation: 785721
Using awk
:
x='123.223.224'
awk 'BEGIN{FS=OFS="."} {for (i=NF; i>=2; i--) printf $i OFS; print $1}' <<< "$x"
224.223.123
Upvotes: 2