Results 1 to 6 of 6
Hey,
the text line is always a full path, examples:
/test/test2/test3/test.file
/test/test2/test3/test4/test5/.....test.file134
I need to extract the directory name, so
so output will be:
/test/test2/test3/
/test/test2/test3/test4/test5/
I've tryd using sed ...
- 10-14-2008 #1Just Joined!
- Join Date
- Oct 2008
- Posts
- 10
Extract pattern from text line
Hey,
the text line is always a full path, examples:
/test/test2/test3/test.file
/test/test2/test3/test4/test5/.....test.file134
I need to extract the directory name, so
so output will be:
/test/test2/test3/
/test/test2/test3/test4/test5/
I've tryd using sed but it didn't work out that well, I ended up getting the oposite results:
echo /test/test2/test3/noname.rar | sed 's/\/.*\///'
gives noname.rar :/
- 10-14-2008 #2Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251
command dirname is the answer
cat file_list | while read line; do echo `dirname $line`; done
- 10-15-2008 #3Linux Newbie
- Join Date
- Jul 2008
- Posts
- 181
Well, yes, obviously. What you are saying is: replace any string starting and ending with "/" with nothing. Clearly, the longest string matching that pattern is "/test/test2/test3/", which gets replaced with the empty string. What you need is the opposite: you need to replace the longest string not containing any "/" at the end of the string, i.e. something like:
That having been said, you probably should use dirname anyway, like secondmouse suggested.Code:sed 's|[^/]\+$||'
- 10-16-2008 #4Linux User
- Join Date
- Aug 2006
- Posts
- 458
in bash, no need for external commands
Code:# s=/test/test2/test3/test.file # echo ${s%/*} /test/test2/test3
- 10-16-2008 #5Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251
ghostdog74, I just found out your solution is not just simpler, also better, as dirname will fail on situation like this:
s="/test/test2/test3/test doc" #(file name contains space)
dirname $s
bash exits with status 1 and prints:
dirname: extra operand `doc'
Try `dirname --help' for more information.
Edit:
actually to make dirname work in this situation is to use double quotations around $s
dirname "$s"
- 10-16-2008 #6Linux User
- Join Date
- Aug 2006
- Posts
- 458
that's because you did not put quotes around your variable


Reply With Quote
