regex - Find substring and delete parent substring using sed
问题描述
I have a problem with using sed that I can't seem to find a way to resolve. I am needing to find for a substring, then delete a parent substring.
Here are the steps I wanting to achieve:
- Find
sourceMappingURL=
in the file - Delete the parent substring starting at
//# sourceMappingURL
and ending at.map
Here is a sample input and output I am expecting:
Input
!function(e){var n={};function t(i){if(n[i])return n[i].exports; //more code
//# sourceMappingURL=bundle.js.map
Output
!function(e){var n={};function t(i){if(n[i])return n[i].exports; //more code
The reason I am doing it this way instead of deleting the line that contains the substring is that for some reason for some of the js files it doesn't just delete that line, it deletes the one above.
My command that deletes the line with the substring looks like:
find my_folder -type f -name "*.js" | xargs sed -i.bak '/sourceMappingURL=/d'
I am not very good with regex, and tried the following but didn't work (\/\/\# sourceMappingURL){1}(\w.*)(\.map){1}
, (\/\/#)(\w.*)(map)
doesn't seem to work either.
解决方案
You can use either of
sed -i.bak '/^\/\/#[[:blank:]]*sourceMappingURL.*\.map$/d'
sed -i.bak 's,^//#[[:blank:]]*sourceMappingURL.*\.map,,'
The first sed
command finds
^
- start of string\/\/#
- a//#
string[[:blank:]]*
- zero or more horizontal whitespacessourceMappingURL
- a subtring.*
- any text up to and including\.map
- a.map
substring at the...$
- end of string
and d
eletes the line where the match was found.
The second command only deletes the contents of the same line since the action is to s
ubstitute the match with an empty string (,
regex delimiter is used to avoid matching /
chars in the LHS).
推荐阅读
- api - Azure API 通过 API 将文件上传到 blob url
- flutter - 是否可以有多个相同类型的 Riverpod ChangeNotificationProviders?
- python - 如何在 jupyter notebook 的 long 函数中采用 markdown 功能?(Python)
- reactjs - 如何从使用钩子开发的 React 应用程序中使用 Dixie Observable?
- reactjs - 如何将提交按钮添加到 react-form-builder2
- reactjs - Next.config.js 使用 next-images 进行配置
- javascript - 如何测试复杂的树结构?
- python - 散景滑块不更新数据
- android - 检测与 PC 的 USB 连接的智能手机应用程序。本地人
- wordpress - 通过 Unity WebGL 应用程序(WP + WC)将商品添加到购物车