Splitting Strings with AWK

If you write a scripts that needs to split a string, e.g. a filepath, then awk(1) is the tool of choice. The following little script does just that.


splitstring.sh


#!/bin/sh

###########################################
##### split a string


if [ $# -ne 1 ] ; then
	echo usage: split_string.sh path
	exit 1
fi

# get the left part of the last "/" 

VAR_1=$(awk -v value=$1 'BEGIN { 
	string = "";
	n = split(value, a, "/");

	for(i = 2; i < n; i++) 
		string = string"/"a[i];

	string = string"/";
	print string;
	}')

echo $VAR_1

# get the right part of the last "/"

VAR_2=$(awk -v value=$1 'BEGIN { 
	n = split(value, a, "/");
	print a[n];
	}')

echo $VAR_2

exit 0