so I am aware there are numerous posts trying to solve this question; however, I have had not succeeded in achieving that! So I have a script that tells me the directory from where my bash script is located which I took from another post:
#SCRIPT_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
/home/vMX-ENV/vMX-21.1R1/scripts/boot
I am trying to remove the /scripts/boot directory from the result so it would end up being:
/home/vMX-ENV/vMX-21.1R1/
I am trying to use awk
as my solution, I know there are other commands like grep or perl but I rather use awk just to keep it consistent. Does anyone know how can I achieve that? I have had so many unsuccessful attempts
Someone suggested on another post to use
awk '/foo/{if (a && a !~ /foo/) print a; print} {a=$0}' file
But I couldn't make it work. Additionally, I have not much experience with bash so I couldn't figure out a way to solve it. Any help?
CodePudding user response:
Your question isn't clear but maybe this is what you're trying to do, i.e. just populate SCRIPT_DIR with the path to the directory 2 levels above the one where your script exists?
SCRIPT_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )/../.." &> /dev/null && pwd )"
CodePudding user response:
Here is an AWK command which deletes the trailing part:
$ echo /home/vMX-ENV/vMX-21.1R1/scripts/boot | awk 'match($0, "/scripts/boot$") { print substr($0, 1, RSTART - 1) }'
/home/vMX-ENV/vMX-21.1R1
CodePudding user response:
Instead of using awk
, you could use sed
, as in:
echo /home/vMX-ENV/vMX-21.1R1/scripts/boot | sed 's/scripts\/boot$//'
This will give you as output:
/home/vMX-ENV/vMX-21.1R1/