-2

How to realize in sed (regex) the next output? It is necessary to extract the preceded '../'

input

$ ../some/path
$ ../../some/path
$ ../../../any/path/to/folder
$ ../../../../path/to/some/folder

output

$ ../
$ ../../
$ ../../../
$ ../../../../
stacker
  • 87
  • 8

2 Answers2

0

I would just do:

sed 's@/[^.].*@/@' 

or (depending on the input and desired behavior):

sed -E 's@/[^.]+@/@'
William Pursell
  • 204,365
  • 48
  • 270
  • 300
-1

Match all repeated ../ prefixes from the beginning and replace the rest with nothing:

s#^((\.\./)*).*$#\1#g

with extended regular expressions, or with basic regular expressions:

s#^\(\(\.\./\)*\).*$#\1#g
  • ^ matches beginning of line
  • (\.\./) matches ../
  • * repeats 0 or more times
  • .*$ matches the rest until the end of line
  • \1 references the first capturing group match

BUT this is probably achieved easier with grep instead of sed, since you do not need to do the replacing (so likely a bit faster too):

egrep -o '^(\.\./)*'

-o prints only the matching portion of the line.

knittl
  • 246,190
  • 53
  • 318
  • 364