如何在脚本中按指定条件切割含特殊字符的文本?
问题:移除myfile.txt中指定前缀文本的正确方法
我的文件myfile.txt内容如下:
{"total":25,"p":1,"ps":100,"paging":{"pageIndex":1,"pageSize":100,"total":25},"issues":[{Lorem Ipsum is simply dummy text of}, {the printing and typesetting industry. Lorem Ipsum has been the industry's}, {standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a}, {type specimen book.}
需要移除的文本是:
{"total":25,"p":1,"ps":100,"paging":{"pageIndex":1,"pageSize":100,"total":25},"issues":[
期望处理后的输出:
{Lorem Ipsum is simply dummy text of}, {the printing and typesetting industry. Lorem Ipsum has been the industry's}, {standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a}, {type specimen book.}
我尝试了以下命令,但结果不符合预期:
cat myfile.txt | sed 's/{"total"//g' | sed 's/"issues":[//g'
错误原因
你的命令存在两个核心问题:
sed替换模式中的{、[是正则特殊元字符,未转义会导致匹配逻辑失效;- 仅单独替换
{"total"和"issues":[两个片段,会残留中间的冗余文本,无法实现删除整个前缀的需求。
正确解决方法
方法1:移除从{"total"开头到"issues":[结尾的整段前缀
直接匹配完整前缀片段,注意转义特殊字符:
sed 's/{"total":.*"issues":\[//' myfile.txt
{"total":.*"issues":\[:匹配从{"total":开始,到"issues":[结束的所有内容(.*匹配任意字符,\[转义[避免正则解析);s/匹配内容//:将匹配到的前缀替换为空,保留后续目标文本。
方法2:移除"issues":[之前的所有文本(包含该标识)
如果前缀格式可能变化,但"issues":[是固定分隔点,可使用更通用的写法:
sed 's/.*"issues":\[//' myfile.txt
.*"issues":\[:匹配从行首到"issues":[的全部内容,替换为空即可得到目标结果。
直接修改原文件(可选)
加上-i参数可直接修改原文件(建议先备份):
sed -i 's/.*"issues":\[//' myfile.txt
内容的提问来源于stack exchange,提问作者Zero5
相关产品推荐
相关产品推荐

