Split a string in shell and get the last field

How to split a string in shell and get the last field. in this tutorial, i written a small program use bash script split string /www/huu/phan/com/xyz to new path /www/huu/phan/com and last field of new path /www/huu/phan/com is com.

Introduction

Input:
  • one_path is /www/huu/phan/com/xyz
Output:
  • new_path is  /www/huu/phan/com
  • last_field of new_path is com
My bash shell as below:
#!/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:

Comments

Popular posts from this blog

zimbra some services are not running [Solve problem]

Bash script list all IP addresses connected to Server

How to install php7 on centos 6