Reputation: 303
Is there a way to insert a colon 4 chars before the end of a string? For example, I have 0x2aab3f439000 and I need 0x2aab3f43:9000
Thanks
Upvotes: 3
Views: 4818
Reputation: 52030
An other pure bash answer:
sh$ V=0x2aab3f439000
sh$ echo ${V::(-4)}:${V:(-4)}
0x2aab3f43:9000
Upvotes: 1
Reputation: 88776
a=0x2aab3f439000
echo ${a:0:-4}:${a#${a:0:-4}}
Output:
0x2aab3f43:9000
Upvotes: 1
Reputation: 81012
$ s=0x2aab3f439000
$ echo "${s:0:(${#s}-4)}:${s:(-4)}"
0x2aab3f43:9000
Alternative (from glenn jackman):
echo "${s%????}:${s: -4}"
Upvotes: 5
Reputation: 1432
RESULT="$( \
echo -n $ORIG | head -c $(( $(echo -n "$ORIG" | wc -c) - 4)) && \
echo -n : && \
echo -n $ORIG | tail -c 4 \
)"
Proof of concept:
me@ ~$ ORIG="hello world"
me@ ~$ RESULT="$( \
> echo -n $ORIG | head -c $(( $(echo -n "$ORIG" | wc -c) - 4)) && \
> echo -n : && \
> echo -n $ORIG | tail -c 4 \
> )"
me@ ~$ echo "$RESULT"
hello w:orld
There are certainly more elegant ways of doing this, but it's hard to beat this for clarity.
Upvotes: 0
Reputation: 785611
Using sed you can do:
s='0x2aab3f439000'
sed 's/.\{4\}$/:&/' <<< "$s"
0x2aab3f43:9000
Upvotes: 8