I would like to have a bash function that prints the specific column of a given string.
My solution works fine but it is verbose and looks ugly to me.
Code:
#!/bin/bash
function get_ip_segment() {
case "$2" in
1)
printf "%s" "$(echo $1 | awk -F '.' '{print $1}')"
;;
2)
printf "%s" "$(echo $1 | awk -F '.' '{print $2}')"
;;
3)
printf "%s" "$(echo $1 | awk -F '.' '{print $3}')"
;;
4)
printf "%s" "$(echo $1 | awk -F '.' '{print $4}')"
;;
*)
printf "%s" "$1"
;;
esac
}
IP="12.34.56.78"
echo $IP
echo "$(get_ip_segment $IP 1)"
echo "$(get_ip_segment $IP 2)"
echo "$(get_ip_segment $IP 3)"
echo "$(get_ip_segment $IP 4)"
Output:
12.34.56.78
12
34
56
78
Then I tried to optimize this code by removing the switch
structure, but it printed an unexpected output.
printf "%s" "$(echo $1 | awk -F '.' '{print column_id}' column_id=$2)"
Output:
1
2
3
4
But somehow, the variable substitution does not work correctly inside awk
.
That could be great if I could have a one-line long function instead of this verbose one.