I have a variable with the contents "eth0 eth1 bond0", is there a way using sed or a similar tool to move anything matching bond.*
to the beginning of the line?
views:
237answers:
2
+2
A:
Using nothing but Bash:
$ var="eth0 eth1 bond0"
$ [[ $var =~ (.*)\ (bond.*) ]]
$ var="${BASH_REMATCH[2]} ${BASH_REMATCH[1]}"
$ echo "$var"
bond0 eth0 eth1
Edit:
This version handles multiple occurrences of "bond" anywhere within the string:
var="eth0 bond0 eth1 bond1 eth2 bond2"
for word in $var
do
if [[ $word =~ bond ]]
then
begin+="$word "
else
end+="$word "
fi
done
var="$begin$end"
var="${var%* }" # if you need to strip the trailing space
echo "$var"
Output:
bond0 bond1 bond2 eth0 eth1 eth2
Dennis Williamson
2010-01-02 05:12:38
thank you, it's useful to have both scenarios covered, single and multiple instance of bond.* :)
f10bit
2010-01-02 12:43:01
+3
A:
you can also use awk
echo "eth0 bond1 eth1 bond0 eth2 bond2" | awk '{
for(i=1;i<=NF;i++)
if($i~/bond/){a[++d]=$i}
else{b[++e]=$i}
}END{
for(i=1;i<=d;i++){
printf a[i]" "
}
for(i=1;i<=e;i++){
printf b[i]" "
}
}'
output
$ ./shell.sh
bond1 bond0 bond2 eth0 eth1 eth2
ghostdog74
2010-01-02 05:40:47