Warm tip: This article is reproduced from serverfault.com, please click

Find substring and delete parent substring using sed

发布于 2020-11-27 21:56:40

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:

  1. Find sourceMappingURL= in the file
  2. 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.

Questioner
Charklewis
Viewed
0
Wiktor Stribiżew 2020-11-28 19:25:52

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 whitespaces
  • sourceMappingURL - a subtring
  • .* - any text up to and including
  • \.map - a .map substring at the...
  • $ - end of string

and deletes the line where the match was found.

The second command only deletes the contents of the same line since the action is to substitute the match with an empty string (, regex delimiter is used to avoid matching / chars in the LHS).