【问题标题】:How to add a custom path to : " ls -d */ "如何添加自定义路径:“ls -d */”
【发布时间】:2020-01-31 09:56:29
【问题描述】:

问题:代码工作正常,它以相反的顺序列出具有“数字名称”的文件夹,但是我必须在同一个目录中。我想为其添加一个自定义路径,这样我就不必在同一个目录中。

ls -d */ |  cut -d '/' -f 1 | sort -nr

我尝试在上面的代码中添加“/test/path”,但没有成功。

ls -d */ /test/path/ |  cut -d '/' -f 1 | sort -nr

更新:我不知道为什么在这种情况下会在底部打印“test2”。我正在使用SliTaz Linux 5.0 我无法弄清楚shell 版本。

root@s1:/# mkdir /test
root@s1:/# mkdir /test/test2
root@s1:/# cd /test/test2/
root@s1:/test/test2# mkdir 1 2 3 10
root@s1:/test/test2# touch test.txt
root@s1:/test/test2# ls -d /test/test2/*/ | awk -F'/' '{print $(NF-1)}' | sort -nr
10
3
2
1
test2
root@s1:/test/test2#

更新 2: 我相信在我使用“Alpine Linux”版本“3”的云服务器上,似乎没有问题,代码工作正常。

test:/# mkdir /test
test:/# mkdir /test/test2
test:/# cd /test/test2
test:/test/test2# mkdir 1 2 3 10
test:/test/test2# touch test.txt
test:/test/test2# ls -d /test/test2/*/ | awk -F'/' '{print $(NF-1)}' | sort -nr
10
3
2
1
test:/test/test2#

【问题讨论】:

  • ls -d /test/test2/*/ | awk 1 在有问题的机器上产生了什么?接受的答案应该是可移植的;我推测您的目录树包含的内容比您透露的要多。
  • @tripleee,看起来一切正常。 /test/test2/1/ /test/test2/10/ /test/test2/2/ /test/test2/3/ /test/test2/test.txt 也许出于便携性考虑,我可以使用“test=$(cd /test/test2/ ; ls -d */ | awk -F'/' '{print $(NF-1)}' | sort -nr)”和..echo $test,但可能缺少new lines
  • @SümerKolçak,我猜test.txt 不是目录?键入ls -d /test/test2/*/ 时不应打印它。我在网上搜索,它说你的机器有ash 作为默认shell。我对您在ash 中如何做到这一点没有任何好主意。
  • @Mihir,我刚刚注意到,你是对的。 @tripleee,我收回,似乎有问题,它将文件列为文件夹。在我的带有 Alpine Linux 的云服务器上不会发生:ls -d /test/test2/*//test/test2/1/ /test/test2/10/ /test/test2/2/ /test/test2/3/
  • 我无法重现,虽然我的 Alpine 有 Busybox,而不是 Ash:pastebin.com/qUYDKY7J

标签: bash shell sorting cut ls


【解决方案1】:
ls -d /test/path/*/ |  cut -d '/' -f 1 | sort -nr

虽然cut 不会按照您打算使用的方式工作。

改用这个:

ls -d /test/path/*/ | awk -F'/' '{print $(NF-1)}' | sort -nr

同样为了避免nullglob,在此之前设置:

shopt -s nullglob

这样,如果没有目录存在,它不会导致错误。

我不确定上述命令在SliTaz Linux 5.0 上不起作用的原因,但正如所讨论的,可以改为这样做:

cd /test/path/ ; ls -d */ | awk -F'/' '{print $(NF-1)}' | sort -nr ; cd "$OLDPWD"

(cd /test/path/ ; ls -d */ | awk -F'/' '{print $(NF-1)}' | sort -nr) 

【讨论】:

  • 这个最后也打印了“test2”。 “test2”文件夹中没有“test2”。 ls -d /test/test2/*/ | awk -F'/' '{print $(NF-1)}' | sort -nr
  • @SümerKolçak,无法重现,您使用的是哪个 shell 版本?
  • 还有ls -d /test/test2/*/ 的输出,你能在你的问题中更新一下吗?
  • 我已经更新了这个问题。 ls -d /test/test2/*/ 的输出是:/test/test2/1/ /test/test2/2/ /test/test2/test.txt /test/test2/10/ /test/test2/3/
  • 我选择您的答案为“选择的答案”,因为您的代码在我的使用“Alpine Linux”的云服务器上运行。所以也许你的代码也可以在其他地方工作,也许问题出在我使用“Slitaz Linux 5”的家用电脑上,我在我的问题中添加了“Update 2”,以表明代码在“Alpine Linux”上运行
猜你喜欢
  • 1970-01-01
  • 2018-09-10
  • 1970-01-01
  • 2012-12-06
  • 2013-07-30
  • 2019-07-18
  • 2023-02-10
  • 2016-03-26
  • 1970-01-01
相关资源
最近更新 更多