BASH/SED - 删除字符串开头和结尾的更好方法?
BASH/SED - Better way of removing the start and end of a string?
这是我目前使用的:
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[@]}"
这是我目前使用的:
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[@]}"