I'm using PWD to get the present working directory. Is there a SED or regex that I can use to, say, get the full path two parents up?
I'm using PWD to get the present working directory. Is there a SED or regex that I can use to, say, get the full path two parents up?
Here's the regex that works for me. It's a little different between grep and Perl/sed:
The extended regex breaks up paths into 0 or more groups of /ABC123 anchored to the end of line, essentially working backward. (.*) consumes everything prior to this match and replaces it.
user@home:~/adir/bdir$ pwd
/home/user/adir/bdir
user@home:~/adir/bdir$ pwd | perl -pe 's|(.*)((/.*?){0})$|\1|'
/home/user/adir/bdir
user@home:~/adir/bdir$ pwd | perl -pe 's|(.*)((/.*?){1})$|\1|'
/home/user/adir
user@home:~/adir/bdir$ pwd | sed -r 's|(.*)((/.*?){2})$|\1|'
/home/user
user@home:~/adir/bdir$ pwd | sed -r 's|(.*)((/.*?){3})$|\1|'
/home
user@home:~/adir/bdir$ pwd | sed -r 's|(.*)((/.*?){4})$|\1|'
Grep can simulate substitution using a positive look ahead (?= which tells grep to match everything except the pattern. -Po tells grep to use Perl regex and show only the match.
user@home:~/adir/bdir$ pwd
/home/user/adir/bdir
user@home:~/adir/bdir$ pwd | grep -Po '(.*)(?=((/.*?){0})$)'
/home/user/adir/bdir
user@home:~/adir/bdir$ pwd | grep -Po '(.*)(?=((/.*?){1})$)'
/home/user/adir
user@home:~/adir/bdir$ pwd | grep -Po '(.*)(?=((/.*?){2})$)'
/home/user
user@home:~/adir/bdir$ pwd | grep -Po '(.*)(?=((/.*?){3})$)'
/home
user@home:~/adir/bdir$ pwd | grep -Po '(.*)(?=((/.*?){4})$)'
Of course it works equally well for Windows style paths:
C:\home\user\adir\bdir> cd
C:\home\user\adir\bdir
C:\home\user\adir\bdir> cd | perl -pe 's|(.*)((\\.*?){0})$|\1|'
C:\home\user\adir\bdir
C:\home\user\adir\bdir> cd | sed -r 's|(.*)((\\.*?){1})$|\1|'
C:\home\user\adir
C:\home\user\adir\bdir> cd | grep -Po '(.*)(?=((\\.*?){2})$)'
C:\home\user
C:\home\user\adir\bdir> cd | grep -Po '(.*)(?=((\\.*?){3})$)'
C:\home
C:\home\user\adir\bdir> cd | grep -Po '(.*)(?=((\\.*?){4})$)'
C:
Sorry for the edits but I've been working on this enigma for about 16 hours now. Just kept trying different permutations and re-reading the regex docs. It had to sink in eventually.