这是我目前使用的:
echo /home/user/yolo/123/swag | sed 's,/home/user/,,' | sed 's,swag,,'
有没有更好的方法可以做到这一点?
您可以在 bash 中使用参数扩展:
path=/home/user/yolo/123/swag
path=${path#/home/user/} # Remove from left.
path=${path%swag} # Remove from right.
echo "$path"
更新
对于路径数组,代码非常相似:
path=(/home/user/file/1/swag /home/user/file/2/swag /home/user/different/path/swag)
path=(${path[@]#/home/user/}) # Remove from left.
path=(${path[@]%swag}) # Remove from right.
echo "${path[@]}"