這仍然是一個循環,因爲它在sed
使用分支命令:
find -depth -type d |sed 'h; :b; $b; N; /^\(.*\)\/.*\n\1$/ { g; bb }; $ {x; b}; P; D'
基於在info sed
(uniq的工作一樣)的腳本。
編輯這裏是sed
腳本註釋爆發(從info sed
複製和修改):
# copy the pattern space to the hold space
h
# label for branch (goto) command
:b
# on the last line ($) goto the end of
# the script (b with no label), print and exit
$b
# append the next line to the pattern space (it now contains line1\nline2
N
# if the pattern space matches line1 with the last slash and whatever comes after
# it followed by a newline followed by a copy of the part before the last slash
# in other words line2 is different from line one with the last dir removed
# see below for the regex
/^\(.*\)\/.*\n\1$/ {
# Undo the effect of
# the n command by copying the hold space back to the pattern space
g
# branch to label b (so now line2 is playing the role of line1
bb
}
# If the `N' command had added the last line, print and exit
# (if this is the last line then swap the hold space and pattern space
# and goto the end (b without a label)
$ { x; b }
# The lines are different; print the first and go
# back working on the second.
# print up to the first newline of the pattern space
P
# delete up to the first newline in the pattern space, the remainder, if any,
# will become line1, go to the top of the loop
D
這裏是正則表達式是這樣做的:
/
- 啓動模式
^
- 匹配行首
\(
- 啓動捕獲組(返回參考子表達式)
.*
- 零個或多個(*)任意字符(。)
\)
- 端捕獲組
\/
- 一斜槓(/)(其中\
轉義)
.*
- 零個或多個任意字符
\n
- 一個新行
\1
- 副本(在這種情況下,無論是在行的開頭和最後一個斜槓之間)
$
- 匹配行尾
/
- 結束模式
你的榜樣,'找到mydir的-mindepth 2 - 類型d'可以工作,但是當你有多個最大深度時它不會。你是否真的只想列出不包含其他目錄的目錄,或者你是否希望看到特定級別的目錄結構? – Cascabel 2009-10-15 19:17:54
是的,謝謝澄清 - 我的例子是一個簡單的例子。我的確在尋求更爲一般的解決方案。 此外,我期待看到一般的目錄結構,並不真正關心目錄中的文件(所以葉也就意味着在這個上下文中的「葉目錄」)。謝謝。 – amol 2009-10-15 21:09:38