Dean Christian Armada
Dean Christian Armada

Reputation: 7384

Getting the second root folder of current directory using bash script

Let us consider that the current working directory of my script is

/usr/src/app-directory/upload/try.sh

In my script I need to echo appdirectory since is the second root folder of the script and also take note that I need to remove not alphanumeric strings. I was able to echo the root folder which is upload with the code below

#!/bin/bash

echo "$(basename $(pwd))"

and it returns

$ ./try.sh
upload

Upvotes: 0

Views: 377

Answers (2)

anubhava
anubhava

Reputation: 786339

Using single awk command, you can do this:

s='/Users/deanchristianarmada/Desktop/projects/infrastructure-playground/ci'
var=$(awk -F/ 'NF>1{p=$(NF-1); gsub(/[^[:alnum:]]+/, "", p); print p}' <<< "$PWD")
echo "$var"

infrastructureplayground

Upvotes: 1

P.P
P.P

Reputation: 121427

awk might be easier:

var=$(awk -F'/' 'NF>2{print $(NF-1)}' <<<"$PWD" | sed 's/[^a-zA-Z0-9]//g')

Prints the penultimate field (with / as the delimiter).

Upvotes: 1

Related Questions