binary sed replacement

bbe is a “sed for binary files”, and should work more efficiently for large binary files than hexdumping/reconstructing. An example of its use: $ bbe -e ‘s/original/replaced/’ infile > outfile Further information on the man page.

JS replacing all occurrences of string using variable [duplicate]

The RegExp constructor takes a string and creates a regular expression out of it. function name(str,replaceWhat,replaceTo){ var re = new RegExp(replaceWhat, ‘g’); return str.replace(re,replaceTo); } If replaceWhat might contain characters that are special in regular expressions, you can do: function name(str,replaceWhat,replaceTo){ replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, ‘\\$&’); var re = new RegExp(replaceWhat, ‘g’); return str.replace(re,replaceTo); } See … Read more

replace zeroes in numpy array with the median value

This solution takes advantage of numpy.median: import numpy as np foo_array = [38,26,14,55,31,0,15,8,0,0,0,18,40,27,3,19,0,49,29,21,5,38,29,17,16] foo = np.array(foo_array) # Compute the median of the non-zero elements m = np.median(foo[foo > 0]) # Assign the median to the zero elements foo[foo == 0] = m Just a note of caution, the median for your array (with no zeroes) … Read more

Why does re.sub replace the entire pattern, not just a capturing group within it?

Because it’s supposed to replace the whole occurrence of the pattern: Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. If it were to replace only some subgroup, then complex regexes with several groups wouldn’t work. There are several possible solutions: Specify pattern in full: … Read more

How to replace a value with the output of a command in a text file?

In general, do use this syntax: sed “s/<expression>/$(command)/” file This will look for <expression> and replace it with the output of command. For your specific problem, you can use the following: sed “s/0/$(date +%s)/g” input.txt > output.txt This replaces any 0 present in the file with the output of the command date +%s. Note you … Read more