编辑以逗号分隔的路径、大小对列表
我有以下形式的行,
parts=/a,1mb,/b/c,2gb,/zee/last,-1 #general form on next line
parts=path1,size1,...,lastPath,-1
我想将所有 path1,size1
except lastplace,-1
替换为 newPath,newSize
> 这样看来
parts=newPathX,newSizeX,lastPath,-1
我想出了如何使用“,”字符的至少一个实例来完成此操作,如下所示,
sed 's|^parts=.*,\(.*,-1\)$|parts=newPathX,newSizeX,\1|gi'
但如果列表仅具有最后一个路径和大小,则此操作会中断。例如,我想
parts=lastPath,-1
转换为
parts=newPathX,newSize,lastPath,-1
所以我尝试用 bash 中的条件来解决这个问题:
egrep -i '^parts=.*,.*,-1$' $file
if [[ $? -eq 0 ]] ; then
sed 's|^parts=.*,\(.*,-1\)$|parts='$new',\1|gi' $inp
else
sed -i -e 's|^parts=|parts='$new',_gi' $file
fi
我想知道一个纯 sed 解决方案,因为我可以快速理解它,但 awk 也可以。
I have lines of the form
parts=/a,1mb,/b/c,2gb,/zee/last,-1 #general form on next line
parts=path1,size1,...,lastPath,-1
I want to replace all path1,size1
except lastplace,-1
with newPath,newSize
so that it looks like
parts=newPathX,newSizeX,lastPath,-1
I figured how to do it using at least one instance of ',' char as follows
sed 's|^parts=.*,\(.*,-1\)$|parts=newPathX,newSizeX,\1|gi'
but this breaks if the list only has the last path and size. For example, I want
parts=lastPath,-1
to be transformed to
parts=newPathX,newSize,lastPath,-1
So I tried to fix this with a conditional in bash:
egrep -i '^parts=.*,.*,-1
I would like to know a pure sed solution as I can quickly understand it, but awk will do too.
$file
if [[ $? -eq 0 ]] ; then
sed 's|^parts=.*,\(.*,-1\)$|parts='$new',\1|gi' $inp
else
sed -i -e 's|^parts=|parts='$new',_gi' $file
fi
I would like to know a pure sed solution as I can quickly understand it, but awk will do too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用 awk:
Try using awk:
有时,它在 sed 中也非常简单;-)。只需在之前添加一个过滤器即可避免出现异常情况
Sometimes, its also very simple in sed ;-). Just add a filter before to avoid your exception case