Huu Phan | Blog Linux operating system | Linux operating system -Blog Huu Phan | www.huuphan.com

This Blog is protected by DMCA.com

huuphan.com. Powered by Blogger.

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:

post new :

Huu Phan | Blog Linux operating system | Huu Phan ~ Zimbra Mail Server,linux,bash script,centos,linux command | www.huuphan.com