在路径中查找并替换文件夹名称

时间:2017-06-21 07:37:00

标签: bash

在我的Bash脚本中,我有一个包含路径的变量。让我们说:

mypath=/a/b/c/d/e

我希望能够用其他东西替换c/d的父文件夹的名称(比如说newB),以便得到:

/a/newB/c/d/e

我该怎么做? 我已经尽力将cut,sed和awk结合起来,但是我得到了很长的命令而没有得到理想的结果。

2 个答案:

答案 0 :(得分:1)

使用参数扩展。

extglob

使用#!/bin/bash mypath=/a/b/c/d/e shopt -s extglob pattern=+([^/])/c/d newpath=${mypath/$pattern/newB/c/d} echo $newpath ,您可以使用替换,这简化了脚本:

{"add-on":[{"ID":2546978,"ActionType":"Added","Add-On-Name":"tetss","Add-On-Price":"3"},{"ID":2546979,"ActionType":"Added","Add-On-Name":"test Addon2","Add-On-Price":"5"},{"ID":2546980,"ActionType":"Added","Add-On-Name":"tdgd","Add-On-Price":"2"}]}

{"Name":"testing ABC","Menu Column Location":"1"}

{"Features":[{"ActionType":"Added","Feature-Option":"25"}]}

{"add-on":[{"ID":2546993,"ActionType":"Updated"}],"sub add-on":[{"ID":"","ActionType":"Added","Sub-Add-On-Description":"des3"},{"ID":"","ActionType":"Added","Sub-Add-On-Description":"des34"},{"ID":"","ActionType":"Added","Sub-Add-On-Description":"des35"}]}

答案 1 :(得分:1)

使用sed

sed -E 's#^(.*/)[^/]+(/c/d/)#\1newB\2#'
  • (.*/)最多匹配/(并放入捕获的组1),后跟一个或多个非/[^/]+)<的字符/ p>

  • 第二个被捕获的群组(/c/d/)字面上匹配/c/d/

  • 在替换中,/c/d/的父级已替换为newB,并且预期会保留捕获的组

示例:

% mypath=/a/b/c/d/e                               

% sed -E 's#^(.*/)[^/]+(/c/d/)#\1newB\2#' <<<"$mypath"
/a/newB/c/d/e