mali184
mali184

Reputation: 61

How to extract filesystem name only without /

For following Sample data and program provided below , please help me to find correct regex .

#cat df.dat
/root                      
/dev/data1                 
/dev/data1/data3
/usr/local/oravg/oradat

what pattern to use to extract root, data1, data3 and oradat without "/"

$ perl grepperl.pl -pattern=' ' df.dat

$ cat grepperl.pl
#! /usr/bin/perl -s -wnl
BEGIN {
# -pattern='RE' switch is required
$pattern or
warn "Usage: $0 -pattern='RE' [ file1 ... ]\n" and
exit 255;
}
/$pattern/ and print;

Upvotes: 1

Views: 110

Answers (5)

Luis Colorado
Luis Colorado

Reputation: 12668

Just anchor you selection to the end of the line and disallow any slash character /.

[^/]*$

See demo

Upvotes: 0

Swadhikar
Swadhikar

Reputation: 2210

Guess this would be more self explanatory:

use File::Basename;

my @paths = qw (/root                      
                /dev/data1                 
                /dev/data1/data3
                /usr/local/oravg/oradat);   

for my $path (@paths) {
    my $dirname  = dirname ($path);
    my $filename = basename ($path);
    print "$path:\n\tFile: $filename\n\tDirectory: $dirname\n\n";
}

1;

Result:

/root:
        File: root
        Directory: /

/dev/data1:
        File: data1
        Directory: /dev

/dev/data1/data3:
        File: data3
        Directory: /dev/data1

/usr/local/oravg/oradat:
        File: oradat
        Directory: /usr/local/oravg

Upvotes: 0

ikegami
ikegami

Reputation: 385799

Perl:

use File::Basename qw( basename );

my $fn = basename($qfn);

bash:

fn="$( basename "$qfn" )"

bash (pipeline):

... | xargs -n 1 basename | ...

Upvotes: 5

slayedbylucifer
slayedbylucifer

Reputation: 23502

Here is a simple bash way (although bash is not tagged in the question)

$ cat test 
/root                      
/dev/data1                 
/dev/data1/data3
/usr/local/oravg/oradat

$ while read line; do echo ${line##*/}; done < test 
root
data1
data3
oradat

Refer Bash Substring Removal for details.

Upvotes: 0

anubhava
anubhava

Reputation: 785156

You can use this negation basedregex in MULTILINE mode:

/[^\/]+$/m

RegEx Demo

[^\/]+$ will match 1 or more of any char that is not / before line end.

Upvotes: 1

Related Questions