linux - 删除文件路径的一部分

标签 linux bash sed

我对脚本编写非常陌生,所以如果这听起来不清楚,我深表歉意。

我有一个文件路径,我想使用 sed 剪切:

文件路径可能类似于:

/to/be/removed/dir1a/keep/this/part
/to/be/removed/dir2b/keep/this/part
/to/be/removed/random/keep/this/part

我想确保,无论我得到哪种格式,我最终都会得到:

/keep/this/partRestored

我找到了类似的示例,但我无法使它们符合上述规范。

编辑

抱歉,问题的原始模板不太清楚。抱歉浪费了您的时间。 我基本上是在 中搜索文件的最新版本。 结果可以是以下任何一种形式:

/home/backup/dir1/destination/file
/home/backup/dir2/destination2/file
/home/backup/folder/destination3/file

换句话说,我总是想删除dir1dir2文件夹之前的所有内容。 并将恢复附加到剩余内容的末尾。 我希望这一点更清楚。感谢您的帮助。

最佳答案

怎么样

 sed -r  's#.*/(dir1|dir2|folder)(/.*$)#\2/restore#g'

测试:

sed -r  's#.*/(dir1|dir2|folder)(/.*$)#\2/restore#g' input
/destination/file/restore
/destination2/file/restore
/destination3/file/restore

编辑

更具体

sed -r  's#.*/(dir1|dir2|folder)[^/]*(/.*$)#\2/restore#g'

测试:

$ echo "/home/backup/dir1_a/destination/file" | sed -r  's#.*/(dir1|dir2|folder)[^/]*(/.*$)#\2/restore#g'
/destination/file/restore

关于linux - 删除文件路径的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26673797/

相关文章:

linux - 在 crontab 中使用 wget 来运行 PHP 脚本

bash - 从 Bash 脚本更改当前目录

linux - 仅当包含在 ""之间时,如何才能替换 CSV 中的逗号字符

python - 如何删除或替换两个模式之间的多行文本

regex - 如何使用正则表达式在列表中每个匹配项的第一次出现周围添加 `\macro{}`

php - 在 Centos 上守护 php 脚本

python - 在 python 中保护 child 与 parent 的通信

linux - 无法使 QWindow::fromWinId 正常工作

python - 特别是本地 Django 部署。织物?

bash - 重建 $@ 并在 Bash 中保留正确的单词拆分