2

To read last value generated using grep/sed/awk command

[root@test 4]# pwd
/opt/lib/insta/4

from above pwd to read value 4.

i am trying something like this which is not correct exactly

pwd | grep -oP 'insta/?'
AK90
  • 428
  • 1
  • 4
  • 16
  • 1
    Use `echo "${PWD##*/}"` – anubhava Jul 09 '21 at 08:17
  • 1
    Could you please confirm if you always want last value in path irrespective of either `insta` is present or not? Or you want to have lst value of `pwd` when insta is present as 2nd last path in it? Please confirm once. – RavinderSingh13 Jul 09 '21 at 08:28
  • @RavinderSingh13 it would be good if we are not looking for insta .. so whichever the path's, when command is executed the last value should get displayed – AK90 Jul 09 '21 at 08:32

2 Answers2

1

Without using any external utility, you can do this in bash:

echo "${PWD##*/}"

4

Or using awk:

awk -F/ '{print $NF}' <<< "$PWD"

4
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

You could set the field separator to / and print the last field if the second last field is insta

pwd | awk -F / '{
  if ($(NF-1) == "insta") {
    print $NF
  }
}'

Output

4

Or you could print the last field:

pwd | awk -F / '{print $NF}'
The fourth bird
  • 154,723
  • 16
  • 55
  • 70