Linux Bash脚本Shell脚本
需要bash脚本来显示文件Linux Bash脚本Shell脚本,linux,bash,shell,Linux,Bash,Shell,需要bash脚本来显示文件 #!/bin/bash my_ls() { # save current directory then cd to "$1" pushd "$1" >/dev/null # for each non-hidden (i.e. not starting with .) file/directory... for file in * ; do # print file/direcotry name if it really exists..
#!/bin/bash
my_ls() {
# save current directory then cd to "$1"
pushd "$1" >/dev/null
# for each non-hidden (i.e. not starting with .) file/directory...
for file in * ; do
# print file/direcotry name if it really exists...
test -e "$file" && echo "$2$file"
# if directory, go down and list directory contents too
test -d "$file" && my_ls "$file" "$2 "
done
# restore directory
popd >/dev/null
}
my_ls
预期产出:
file1
file2
info (directory)
data
stuff (directory)
input
output
scripts (directory)
doit
helper
testinput
jobs
results (directory)
bob
dave
mary
下面是一个bash脚本,它可以满足您的要求
$ cat tree
#!/bin/bash
# tree [DIR]
ls_tree() {
dir="${1:-.}"
while read name ; do
if [[ -n "$name" ]]; then
if [[ "$name" =~ :$ ]]; then
dir="${name%:}"
else
echo "$dir/${name%*}"
fi
fi
done
}
show_tree() {
sed -e 's|^./||' | sort | sed -e 's|/$||' -e 's|[^/]*/| |g'
}
/bin/ls -1RF "${1:-.}" | ls_tree "${1:-.}" | show_tree
以下是一个示例输出:
$ tree
fun.rb
fun
data
filter.awk
good
inputtest.sh
reqs
test1.awk
input
pairs
pairs.sh
split-collections
indir
col1
col2
col3
outdir
file1
file2
file21
file22
file23
file3
file31
file32
file33
split-collections.sh
t1
tree1
这是一个基本的单线解决方案:
find . -type d -printf '%p (directory)\n' -o -print | LC_ALL=C sort | sed 's:[^/]*/: :g'
为了可读性,将同一代码拆分为多行:
find . -type d -printf '%p (directory)\n' -o -print |
LC_ALL=C sort |
sed 's:[^/]*/: :g'
LC_ALL=C
是为了防止sort
根据区域设置做奇怪的事情。网络上有很多解决类似问题的方法。尝试搜索查找sed树
。第一个问题是StackOverflow问题:
请注意,此解决方案在Mac OS上不起作用,因为它的“查找”是一个不支持“-printf”选项的旧解决方案。我建议使用
find
命令并重新格式化其输出。@Jdamian这正是我需要的文件1、文件2,作业只是我们需要显示的文件(目录下的目录)如果您知道find
命令,只需开始创建代码并对其进行测试。如果不起作用,向我们展示代码及其输出;那我们就可以帮助你了。正如@Celeo所提到的,这不是一个编码服务。如何在目录前面打印(目录)?如何在目录前面添加目录?我应该在哪里添加(目录)?要插入“(目录)”,请修改“show_tree”中的sed命令:sed-e的| ^./| | |排序| sed-e的| ^(.*)/$|(目录)\1 |'-e的| ^[/]*/|你能帮我一下吗这不是wrking@user4186509,我已经在几个系统上测试了一行程序(从Stackoverflow页面剪切和粘贴),没有发现明显的问题。你看到了什么问题?您是否收到错误,或者输出不是您期望的结果?@user4186509,我怀疑您有剪切粘贴错误。代码中的所有引号都匹配。也许有些角色在长队结束时迷路了。我在答案中添加了一个多行版本,所以也许可以尝试使用它。@user4186509,我修改了答案,说它在Mac OS上不起作用。这个问题有一个“linux”标签,所以我认为只使用linux的解决方案是可以接受的。它可以修改为在Mac OS上工作,但是在输出中获取“(目录)”字符串会很混乱。@user4186509,去除“.”行的一个选项是在find
:find..之后立即将tail-n+2
放入管道中tail-n+2 | LC|u ALL=C sort |……
@user4186509,此操作的输出可能更接近您想要的:find-键入d-printf“%P(目录)\n'-o-printf“%P\n”| tail-n+2 | LC|u ALL=C sort | sed's:[^/]*/::g'
。