Hello,
I would like to extract one or two fields of a line.
At the moment, I am extracting the first field of a line:
command | cut -f 1 -d '.' > file
The line can have two or three fields delimited with a dot.
if three fields, I want to be able to get the first two
ie if line = X.Y.Z
output X.Y
if two fields, I want to be able to get the first one only.
ie if line = X.Y
output X
How can I do this ?
Thank you for any help
Max
denn
December 17, 2007, 9:53am
2
#!/usr/bin/ksh
NOF=`echo $1 | awk -F. '{ print NF}'`
case $NOF in
2)
echo $1 | awk -F. '{ print $1}'
;;
3)
echo $1 | awk -F. '{ print $1 "." $2}'
;;
esac
or
[[ `echo $1 | awk -F. '{ print NF}'` -eq "2" ]] && print $1 | awk -F. '{ print $1}' || print $1 | awk -F. '{ print $1 "." $2}'
maxvirrozeito:
Hello,
I would like to extract one or two fields of a line.
At the moment, I am extracting the first field of a line:
command | cut -f 1 -d '.' > file
The line can have two or three fields delimited with a dot.
if three fields, I want to be able to get the first two
ie if line = X.Y.Z
output X.Y
if two fields, I want to be able to get the first one only.
ie if line = X.Y
output X
How can I do this ?
Thank you for any help
Max
printf "%s\n" "${line%.*}"
I mean:
$ printf "X.Y.Z\n"|while IFS= read -r;do printf "%s\n" "${REPLY%.*}";done
X.Y
$ printf "X.Y\n"|while IFS= read -r;do printf "%s\n" "${REPLY%.*}";done
X
If you read doesn't support the -r switch, remove it.
If your shell support process substitution:
$ { read;printf "${REPLY%.*}";}< <(printf "X.Y.Z\n")
X.Y
$ { read;printf "${REPLY%.*}";}< <(printf "X.Y\n")
X
Where the second printf is your command.
Thank you for your answers !
It fixes my problem
Max