文件结构如下:
34945,/data/file/system01/data/system/backups/filename.txt
393092,/data/file/system-03stby/data/system/backups/filename.extra.txt
我所期待的结果是这样的:
34945,/data/system/backups/filename.txt
393092,/data/system/backups/filename.extra.txt
答案1
鉴于
$ cat file
34945,/data/file/system01/data/system/backups/filename.txt
393092,/data/file/system-03stby/data/system/backups/filename.extra.txt
然后
$ sed -E 's:,(/[^/]*){3}:,:' file
34945,/data/system/backups/filename.txt
393092,/data/system/backups/filename.extra.txt
或类似地
$ awk -F, 'BEGIN{OFS=FS} {sub(/([/][^/]*){3}/,"",$2)} 1' file
34945,/data/system/backups/filename.txt
393092,/data/system/backups/filename.extra.txt
无论哪种情况,([/][^/]*){3}
都是一个扩展正则表达式,匹配一个斜杠,后跟零个或多个非斜杠字符,全部匹配 3 次。如果前两个目录是常量,则可以使用类似sed 's:,/data/file/[^/]*:,:'
或 的内容awk -F, 'BEGIN{OFS=FS} {sub(/data[/]file[/][^/]*[/]/,"",$2)} 1'
。
或者在 perl 中拆分和合并:
$ perl -F, -lpe '@p = split /\//, $F[1]; $_ = join ",", $F[0], (join "/", @p[4..$#p])' file
34945,data/system/backups/filename.txt
393092,data/system/backups/filename.extra.txt
答案2
另一种 Perl 方法,基本思想与@steeldriver 的回答,但更简洁:
$ perl -F'[,/]' -nle 'print "$F[0],/",join("/",@F[5..$#F])' file
34945,/data/system/backups/filename.txt
393092,/data/system/backups/filename.extra.txt
答案3
阅读man cut
并使用cut "-d," -f2- | cut -d/ -f5-
您的文件。