Removing text - ideas?

I am not a programmer, but I tried to make some regular expression and hit the wall. I was hoping to find some help, I am trying to analyze the data in a log file, and I am having the following problem:

I have a test.csv file that consists of several entries of one line from another program that creates the following layout format:

  • d: \ snow \ dir.txt
  • d: \ snow \ story \ dir.tff
  • d: \ snow \ history \ help.jar
  • d: \ winter \ show \ help.txt
  • d: \ summer \ beach \ ocean \ swimming.txt

What I want is to remove the file names from the path list, so the resulting file will contain:

  • d: \ snow \
  • d: \ snow \ story \
  • d: \ snow \ story \
  • d: \ winter \ show \
  • d: \ summer \ beach \ ocean \

perl, . , , , , perl python.

,

+3
4

Perl:

perl -pe 's/[^\\]+$/\n/' <infile.txt >outfile.txt

:

-p Perl ( -e) while, .

-e Perl .

s/[^\\]+$/\n/ - , , , \n.

[^\\] - , ,

[^\\]+ - , ,

[^\\]+$ - , , ,

+4

, , , , . File::Basename File::Spec :

:

use strict;
use warnings;
use v5.10;

use File::Basename;

say dirname($_) for <DATA>;

__DATA__
d:\snow\dir.txt
d:\snow\history\dir.tff
d:\snow\history\help.jar
d:\winter\show\help.txt
d:\summer\beach\ocean\swimming.txt

:

d:\snow
d:\snow\history
d:\snow\history
d:\winter\show
d:\summer\beach\ocean

, , .

File::Spec:

my ($volume, $dir, $file) = File::Spec->splitpath($path);
my $wanted_path = $volume . $dir;  # what you want

, .

+3

You can do it with one liner and

perl -pe s /\\\\\w+\.\w+$// test.csv > Output.txt

\w+\.\w+$ matches the file name with the extension at the end of the path

0
source

Here is one way to do this in Python:

python -c 'import sys,re;[sys.stdout.write(re.sub("[^\\\]+$","\n",l))for l in sys.stdin]' < in.txt > out.txt

I admit this is a bit more verbose than the Perl solution.

0
source

All Articles