Introduction
Input:- one_path is /www/huu/phan/com/xyz
- new_path is /www/huu/phan/com
- last_field of new_path is com
#!/bin/bash
###############
#
# Author: HuuPV
# My blog: www.huuphan.com
#
###############
# How to split a string in shell and get the last field
one_path="/www/huu/phan/com/xyz"
last_slash=-1
for (( i=0; i < ${#one_path}; i++));
do
if [ ${one_path:$i:1} == '/' ]
then
last_slash=$i;
fi
done
new_path=${one_path:0:$last_slash}
last_field=$(basename $new_path)
echo "Old path: $one_path"
echo "New path: $new_path"
echo "Last field of $new_path: $last_field"
The display as picture below:
Thanks for reading Split a string in shell and get the last field My blog Zimbra Mail Server,linux,bash script,centos,linux command I hope this is useful.