Bash - Convert sub.site.com in to com_site_sub?
I am writing a script that will 开发者_运维知识库do some automated things, and it requires to be put in the format <tld>_<site>_<sub>
for now.
I will basically provoke it as such: ./add.sh about.site.com
Which will add the corresponding entries once the name is extracted
How could I write this?
You can mess with $IFS
to change how things like read
parse text:
hostname="foo.bar.com"
IFS=. read sub site tld <<< "$hostname"
echo ${tld}_${site}_${sub}
Or awk (a little cleaner than sed):
echo $1 | awk -F"." '{print $3 "_" $2 "_" $1}'
You could also use sed
:
echo $1 | sed 's/\([^.]*\)\.\([^.]*\)\.\([^.]*\)/\3.\2.\1/'
Lots of backslashes, and it involves two processes, but it could have advantages if you need to handle many such substitutions in a single invocation of the script.
精彩评论