简体   繁体   English

使用bash脚本获取当前目录的第二个根文件夹

[英]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. 在我的脚本中,我需要回appdirectory因为它是脚本的第二个根文件夹,并且还要注意,我需要删除的不是字母数字字符串。 I was able to echo the root folder which is upload with the code below 我能够回显使用以下代码upload的根文件夹

#!/bin/bash

echo "$(basename $(pwd))"

and it returns 它返回

$ ./try.sh
upload

Using single awk command, you can do this: 使用单个awk命令,您可以执行以下操作:

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

awk might be easier: awk可能更容易:

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

Prints the penultimate field (with / as the delimiter). 打印倒数第二个字段(使用/作为分隔符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM