Question

I have a string:

//host:/dir1/dir2/dir3/file_name

I want to fetch value of host & directories in different variables in unix script. Example :

host_name = host
dir_path = /dir1/dir2/dir3

Note - String length & no of directories is not fixed.

Could you please help me to fetch these values from string in unix shell script.

Was it helpful?

Solution

Using bash string operations:

str='//host:/dir1/dir2/dir3/file_name'
host_name=${str%%:*}
host_name=${host_name##*/}
dir_path=${str#*:}
dir_path=${dir_path%/*}

OTHER TIPS

I would do it using regular expressions:

if [[ $path =~ ^//(.*):(.*)/(.*)$ ]]; then
    host="${BASH_REMATCH[1]}"
    dir_path="${BASH_REMATCH[2]}"
    filename="${BASH_REMATCH[3]}"
else
    echo "Invalid format" >&2
    exit 1
fi

If you are sure that the format will match, you can do simply

[[ $path =~ ^//(.*):(.*)/(.*)$ ]]
host="${BASH_REMATCH[1]}"
dir_path="${BASH_REMATCH[2]}"
filename="${BASH_REMATCH[3]}"

Edit: Since you seem to be using ksh rather than bash (though bash was indicated in the question), the syntax is a bit different:

match=(${path/~(E)^\/\/(.*):(.*)\/(.*)$/\1 \2 \3})
host="${match[0]}"
dir_path="${match[1]}"
filename="${match[2]}"

This will break if there are spaces in the file name, though. In that case, you can use the more cumbersome

host="${path/~(E)^\/\/(.*):(.*)\/(.*)$/\1}"
dir_path="${path/~(E)^\/\/(.*):(.*)\/(.*)$/\2}"
filename="${path/~(E)^\/\/(.*):(.*)\/(.*)$/\3}"

Perhaps there are more elegant ways of doing it in ksh, but I'm not familiar with it.

The shortest way I can think of is to assign two variables in one statement:

$ read host_name dir_path <<< $(echo $string | sed -e 's,^//,,;s,:, ,')

Complete script:

string="//host:/dir1/dir2/dir3/file_name"
read host_name dir_path <<< $(echo $string | sed -e 's,^//,,;s,:, ,')
echo "host_name = " $host_name
echo "dir_path = " $dir_path

Output:

host_name:  host
dir_path:  /dir1/dir2/dir3/file_name
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top