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,
- -d/ : use / for field delimiter.
- -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,
- -F/ : sets the field separator, FS, to /.
You should follow me on twitter here or grab rss feed to keep track of new changes.
Featured Articles:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop












{ 7 comments… read them below or add one }
Well, it’s somewhat blurry why exactly the 3rd component required. If it’s about getting parent directory of the current directory it can be solved as follows:
Of course there is a lot of ways to do that, but the cut(1) and awk(1) IMHO the most straightforward ones. Thanks!
In case of need the following prints exactly the “3rd” component in pure shell:
Actually, I forgot about the last pure shell based solution. I appreciate your comment.
Sorry but <<< operator is new to me. What exactly do <<< operator and what is called?
Here string
This is the bash shortcut to Bourne shell’s
@Vivek Gite
@Mishka
Thanks
If in 9th field($9) there is sth like: A/B/C and one needs C. how can we extract C and put it in output?