Unix / Linux Shell: Get Third Field Separated by Forward Slash (/) Delimiter

I‘m writing a shell script for automation purpose. The output the path of the current working directory is stored in $PWD or it can be obtained using the pwd command. How do I find out find out 3rd field separated by the forward slash (/) delimiter using $PWD under Unix like operating systems?

You can display selected parts of lines from each FILE or shell variable using any standard Unix command line utility.

cut Command Example

You can use the cut command as follows:

var="/home/vivek/foo/bar"
cut -d/ -f4 <<<"${var}"

To get the sample value from a shell variable called $PWD, enter:

cut -d/ -f4 <<<"${PWD}"

OR

value=$(cut -d/ -f4 <<<"${PWD}")
echo "$value"

You can replace the variable name with the file name:

cut -d/ -f4 /path/to/file.name

Where,

  1. -d/ : use / for field delimiter.
  2. -f4 : Select only fourth field. Also print any line that contains no delimiter character, unless the -s option is specified.

awk Command Example

awk is a pattern scanning and text processing language. The syntax is as follows:

var="/home/vivek/foo/bar"
awk -F/ '{ print $4}' <<<"${var}"

OR

value=$(awk -F/ '{ print $4}' <<<"${PWD}")
echo "$value"

You can replace the variable name with the file name:

awk -F/ '{ print $4}' /path/to/file.txt

Where,

  1. -F/ : sets the field separator, FS, to /.

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.