0

I have a variable that contains the result of the command whereis ls which is:

ls: /bin/ls /usr/share/man/man1/ls.1.gz

I need to search through this variable and retrieve this specific portion and save it into a new variable, newVar:

/bin

I have tried echo $var | awk '{print $2}' but this grabs /bin/ls

I then need to search through my $PATH variable finding the substring /bin: (I was thinking with my newVar as a match somehow) and somehow remove this portion of $PATH and update $PATH to reflect that change. Quite new to bash scripting and any help would be greatly appreciated.

4
  • 1
    What is output of type ls ? Commented Feb 1, 2020 at 8:03
  • @anubhava i'm not too sure what you mean, when i run type ls on my terminal i get ls is aliased to `ls --color=auto' Commented Feb 1, 2020 at 8:15
  • 1
    Try: whereis ls | awk '{sub(/\/ls$/, "", $2); print $2}' Commented Feb 1, 2020 at 8:19
  • 1
    @anubhava that worked! thank you so much, could I trouble to break the part inside the awk execution block? Commented Feb 1, 2020 at 8:29

3 Answers 3

2

You might just use dirname and which:

dirname "$(which ls)"
Sign up to request clarification or add additional context in comments.

1 Comment

Glad it helped! PS: there is also basename, it's the opposite and gives you the filename without the path.
2
$ echo "$var" | cut -d/ -f2
bin

Comments

1

You may use this awk:

whereis ls | awk '{sub(/\/ls$/, "", $2); print $2}'

sub function strips trailing /ls from 2nd column of whereis output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.