开发者

extract sub expression with sed

开发者 https://www.devze.com 2023-01-12 06:47 出处:网络
I have a list of di开发者_JAVA技巧rectories starting from /root. Eg random text /root/dir1/files random end

I have a list of di开发者_JAVA技巧rectories starting from /root. Eg

random text /root/dir1/files random end

delete me /root/dir1/files/2dir I am waste

/root/examples/source alalalala

/root/example/header some other text

I want to use sed to take from every line the directory and remove everything else. My final output must be

/root/dir1/files

/root/dir1/files/2dir

/root/examples/source

/root/example/header

How can I do it? (extract everything starting from /root... until the end of the path)


Here you go:

sed 's|^[^/]*\(/[^ ]*\).*$|\1|'

This assumes that filenames don't have spaces in them, and the first "/" on the line marks the start of a filename.

Revise as:

sed -n 's|^[^/]*\(/[^ ]*\).*$|\1|p'

to only output lines that match the pattern (no blank lines).


For the sake of gratuitous completeness, I've also included a solution in a few other languages:

Bash

while read LINE; do
  X=${LINE#*/}
  X=${X%% *}; 
  [ "$X" == "" ] || echo /$X
done  

Perl

 perl -ne '/(\/root[^ ]+)/ and print "$1\n"'

Lua

#!lua
while true do
  local line = io.read()
  if line == nil then break end
  s = string.match(line,"/root[^%s]+")
  if s then print(s) end
end


awk '{for(i=1;i<=NF;i++) if ($i ~/\/root/) {print $i} }' file


YET ANOTHER EDIT: Seems that my initial evaluation of the question did not really read it as closely as it should have. Thanks to the commentary below, I've learned a few tricks, and can clear up this answer.

First, tylerl has shown a command that should work for this in sed in this answer. Neat trick, though I'll probably stick to awk for this.

My own solution did not take into account the first couple of lines given in the description. ghostdog74 gives a solution that might work here.

Take a look at the above linked solutions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号