Results 1 to 7 of 7
  1. #1
    Join Date
    Feb 2004
    Posts
    143

    Unanswered: Finding part of the current directory

    I am on a Sun Solaris 5.10

    Suppose say my pwd command gives me :
    /opt/local/sys/data/01/backups

    From the above information, would it be possible by any chance to execute a command that can return me just the the directory name(not the whole path) that is {current directory minus one level}

    In other words, I am looking for a command that can return me
    01

    If my present directory was /opt/local/sys/data/20/ksh , gives me
    20

  2. #2
    Join Date
    Jun 2003
    Location
    Toronto, Canada
    Posts
    5,516
    Provided Answers: 1
    Code:
    pwd | perl -n -e 'split /\//;print $_[@_-2];'
    ---
    "It does not work" is not a valid problem statement.

  3. #3
    Join Date
    Feb 2004
    Posts
    143

    Prompt in the same line

    Thanks Nick. I tried it out and this is what happens

    server01-(/opt/local/sys/data/01/backups)-> pwd | perl -n -e 'split /\//;print $_[@_-2];'

    Gives me

    01server01-(/opt/local/sys/data/01/backups)->

    In other words, I do get 01 but the unix prompt follows right after it and does not get to the new line. Can I make it look like

    01
    server01-(/opt/local/sys/data/01/backups)->

  4. #4
    Join Date
    Jun 2003
    Location
    Toronto, Canada
    Posts
    5,516
    Provided Answers: 1
    Well, how about adding a newline to the print statement? The newline looks like "\n".
    ---
    "It does not work" is not a valid problem statement.

  5. #5
    Join Date
    Sep 2009
    Posts
    44
    If you're going to invoke perl, you may as well do it all in Perl:

    Code:
    perl -MCwd=cwd -e 'print((split(m:/:, cwd))[-2]."\n")'
    A somewhat more readable version:

    Code:
    perl -MCwd=cwd -e '@a = split(m:/:, cwd); print "$a[-2]\n"'
    Otherwise, under bash, you could use something like:

    Code:
    basename `dirname "$PWD"`

  6. #6
    Join Date
    Feb 2004
    Posts
    143
    Thank you. All of them worked just fine in giving me

    01

    Even though I am using korn as my default shell and never switch over to anything at any point, the following worked just fine

    basename `dirname "$PWD"`

    Also keeping in fact, me being a big zero in perl, I would rather play safe and use the basename command.

  7. #7
    Join Date
    May 2005
    Location
    South Africa
    Posts
    1,365
    Provided Answers: 1
    echo $(cd ..; echo ${PWD##*/})

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •