linux中正则表达式仅保留绝对路径的目录

 

001、 方法1

[root@pc1 test2]# ls
a.txt
[root@pc1 test2]# cat a.txt      ## 测试文件
/home/test2/a.txt
[root@pc1 test2]# sed -r 's/(\/.*\/).*/\1/' a.txt     ## 仅保留路径
/home/test2/

 

002、方法2:

[root@pc1 test2]# ls
a.txt
[root@pc1 test2]# cat a.txt        ## 测试数据
/home/test2/a.txt
[root@pc1 test2]# sed 's/[^/]\+$//' a.txt     ## 提取路径
/home/test2/

 

003、方法3:

[root@pc1 test2]# ls
a.txt
[root@pc1 test2]# cat a.txt           ## 测试数据
/home/test2/a.txt
[root@pc1 test2]# sed 's/\S[^/]\+$//' a.txt       ## 提取路径
/home/test2

 

004、方法4

复制代码
[root@pc1 test2]# ls
a.txt
[root@pc1 test2]# cat a.txt          ## 测试文件
/home/test2/a.txt
/home/test2/k.csv
/home/test2/dir01/dirxx/xx.map
[root@pc1 test2]# awk -F "/" '{OFS = "/";$NF = ""; print $0}' a.txt    ## 提取路径
/home/test2/
/home/test2/
/home/test2/dir01/dirxx/
复制代码

 

005、方法5

复制代码
[root@pc1 test2]# ls
a.txt
[root@pc1 test2]# cat a.txt         ## 测试文件
/home/test2/a.txt
/home/test2/k.csv
/home/test2/dir01/dirxx/xx.map
[root@pc1 test2]# awk -F "/" 'NF{NF--; OFS = "/"}1' a.txt   ## 提取路径
/home/test2
/home/test2
/home/test2/dir01/dirxx
复制代码

 

006、方法6

复制代码
[root@pc1 test2]# ls
a.txt
[root@pc1 test2]# cat a.txt                        ##    测试文件
/home/test2/a.txt
/home/test2/k.csv
/home/test2/dir01/dirxx/xx.map
[root@pc1 test2]# cat a.txt | xargs -n 1 dirname    ## 提取路径
/home/test2
/home/test2
/home/test2/dir01/dirxx
复制代码

 。

 

posted @   小鲨鱼2018  阅读(101)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2022-09-19 ubuntu 22.04中利用conda 安装 delly软件
2022-09-19 centos7 中 使用conda安装 Pindel 软件
2022-09-19 centos 7 中使用conda 安装 BreakDancer软件
2022-09-19 centos7 中如何安装anaconda
2022-09-19 linux 系统中wget -O选项
2022-09-19 gcc安装包下载地址
2022-09-19 centos中如何自动获取IP、获取网关
点击右上角即可分享
微信分享提示