linux – 仅列出文件的公共父目录
发布时间:2020-12-31 13:47:38 所属栏目:Linux 来源:网络整理
导读:我正在搜索一个文件,比如“file1.txt”,并且find命令的输出如下所示. /home/nicool/Desktop/file1.txt/home/nicool/Desktop/dir1/file1.txt/home/nicool/Desktop/dir1/dir2/file1.txt 在上面的例子中我只想要共同的父目录,在上面的例子中是“/ home / nicool
我正在搜索一个文件,比如“file1.txt”,并且find命令的输出如下所示. /home/nicool/Desktop/file1.txt /home/nicool/Desktop/dir1/file1.txt /home/nicool/Desktop/dir1/dir2/file1.txt 在上面的例子中我只想要共同的父目录,在上面的例子中是“/ home / nicool / Desktop”.如何使用bash实现?请帮助找到这种问题的一般解决方案. 解决方法此脚本读取行并在每次迭代中存储公共前缀:# read a line into the variable "prefix",split at slashes IFS=/ read -a prefix # while there are more lines,one after another read them into "next",# also split at slashes while IFS=/ read -a next; do new_prefix=() # for all indexes in prefix for ((i=0; i < "${#prefix[@]}"; ++i)); do # if the word in the new line matches the old one if [[ "${prefix[i]}" == "${next[i]}" ]]; then # then append to the new prefix new_prefix+=("${prefix[i]}") else # otherwise break out of the loop break fi done prefix=("${new_prefix[@]}") done # join an array function join { # copied from: https://stackoverflow.com/a/17841619/416224 local IFS="$1" shift echo "$*" } # join the common prefix array using slashes join / "${prefix[@]}" 例: $./x.sh <<eof /home/nicool/Desktop1/file1.txt /home/nicool/Desktop2/dir1/file1.txt /home/nicool/Desktop3/dir1/dir2/file1.txt eof /home/nicool (编辑:南通站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- linux – 我在哪里可以找到GNU ar文件格式规范?
- linux中Nginx与Lua执行顺序详解
- 对int变量赋值的操作是原子的吗?为什么?
- linux – shell脚本如何判断它是否在支持256色的xterm窗口中
- linux中挂载硬盘报错youmustspecifythefilesystemtype
- 10+ commonly using find command switches with example U
- 360手机助手上传APK安装包与手机截图教程
- 再次革新手机行业 OPPO N3即将携“冰巢”发布
- lg nexus5(2015)什么时候出 lg nexus5(2015)什么时候发布
- 愤怒的小鸟返校季13-20关视频三星通关攻略