Globally replace text in several files: Difference between revisions
Content added Content deleted
(Scala solution added) |
(Add Jsish) |
||
Line 696: | Line 696: | ||
| if $ix then .[:$ix] + $to + (.[($ix+$len):] | g) else . end; |
| if $ix then .[:$ix] + $to + (.[($ix+$len):] | g) else . end; |
||
g;</lang> |
g;</lang> |
||
=={{header|Jsish}}== |
|||
'''For the demo, the code does not overwrite the samples, but creates a .new file.''' |
|||
<lang javascript>/* Global replace in Jsish */ |
|||
if (console.args.length == 0) { |
|||
console.args.push('-'); |
|||
} |
|||
/* For each file, globally replace "Goodbye London!" with "Hello New York!" */ |
|||
var fn, data, changed; |
|||
for (fn of console.args) { |
|||
/* No args, or an argument of - uses "stdin" (a special Channel name) */ |
|||
if (fn == 'stdin') fn = './stdin'; |
|||
if (fn == '-') fn = 'stdin'; |
|||
try { |
|||
data = File.read(fn); |
|||
/* Jsi supports the m multiline regexp flag */ |
|||
changed = data.replace(/Goodbye London!/gm, 'Hello New York!'); |
|||
if (changed != data) { |
|||
if (fn == 'stdin') fn = 'stdout'; else fn += '.new'; |
|||
var cnt = File.write(fn, changed); |
|||
puts(fn + ":" + cnt, 'updated'); |
|||
} |
|||
} catch(err) { puts(err, 'processing', fn); } |
|||
}</lang> |
|||
To meet the task specification, change |
|||
<lang javascript>if (fn == 'stdin') fn = 'stdout'; else fn += '.new';</lang> |
|||
to |
|||
<lang javascript>if (fn == 'stdin') fn = 'stdout';</lang> |
|||
removing the else clause. The code will then overwrite originals. |
|||
{{out}} |
|||
<pre>prompt$ cat one |
|||
Goodbye London! it was the slice. |
|||
Goodbye London, should still be here |
|||
And a little more Goodbye London! New York! |
|||
prompt$ jsish global-replace.jsi - <one |
|||
Hello New York! it was the slice. |
|||
Goodbye London, should still be here |
|||
And a little more Hello New York! New York! |
|||
stdout:115 updated</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |