Jay Wehrman
Jay Wehrman

Reputation: 193

BASH: parse a variable with awk

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.

Upvotes: 0

Views: 723

Answers (3)

Ed Morton
Ed Morton

Reputation: 204731

$ echo "$var" | cut -d/ -f2
bin

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 158280

You might just use dirname and which:

dirname "$(which ls)"

Upvotes: 2

anubhava
anubhava

Reputation: 786349

You may use this awk:

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

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

Upvotes: 1

Related Questions