yxian
October 19, 2007, 12:14am
1
Hey,
I'm trying to print the first four characters of the hostname of a computer.
I can get it from using:
hostname -s | sed 's/...........$//'"
but this is when I know how many characters are in the computer name.
I dont understand why some like:
hostname -s | sed '/..../p'
wont work?
Any ideas?
Thanks.
yxian
October 21, 2007, 11:42pm
3
Thanks Mate! I have spent a number of hour trying to find this out?
drl
October 22, 2007, 1:00am
4
Hi.
Because that sed line says: "If the incoming line has 4 characters then print it."
If you wanted to print just the first 4 with sed, you could use:
hostname -s | sed 's/^\(....\).*/\1/'
which seems cumbersome compared to the cut, but sed is capable of much more than cut ... cheers, drl
can try this also
hostname|awk '{print substr($1,1,4)}'
Thanks.
Last 4 characters how can i print
using a similar idea(s) as above......
yxian:
Hey,
I'm trying to print the first four characters of the hostname of a computer.
I can get it from using:
hostname -s | sed 's/...........$//'"
but this is when I know how many characters are in the computer name.
Though longer than some other solutions, this will be much faster because it doesn't use any external commands other than hostname:
hostname=$(hostname)
temp=${hostname#????}
echo ${hostname%"$temp"}
But it is also possible that your shell already has the output of hostname in the variable $HOSTNAME (bash does), and you don't need any external command:
temp=${HOSTNAME#????}
echo ${HOSTNAME%"$temp"}