docs/src/operating-on-all-fields.md
Suppose you want to replace spaces with underscores in your column names:
<pre class="pre-highlight-in-pair"> <b>cat data/spaces.csv</b> </pre> <pre class="pre-non-highlight-in-pair"> column 1,column 2,column 3 apple,ball,cat dale egg,fish,gale </pre>The simplest way is to use mlr rename with -g (for global replace, not just first occurrence of space within each field) and -r for pattern-matching (rather than explicit single-column renames):
You can also do this with a for-loop:
<pre class="pre-highlight-in-pair"> <b>cat data/bulk-rename-for-loop.mlr</b> </pre> <pre class="pre-non-highlight-in-pair"> map newrec = {}; for (oldk, v in $*) { newrec[gsub(oldk, " ", "_")] = v; } $* = newrec </pre> <pre class="pre-highlight-in-pair"> <b>mlr --icsv --opprint put -f data/bulk-rename-for-loop.mlr data/spaces.csv</b> </pre> <pre class="pre-non-highlight-in-pair"> column_1 column_2 column_3 apple ball cat dale egg fish gale </pre>The previous example isn't sufficient when there are carriage returns in the field names. Here we can use the Miller programming language:
<pre class="pre-highlight-in-pair"> <b>cat data/header-lf.csv</b> </pre> <pre class="pre-non-highlight-in-pair"> "field A",field B 1,2 3,3 6,6 </pre> <pre class="pre-highlight-in-pair"> <b>mlr --csv --from data/header-lf.csv put '</b> <b> map inrec = $*;</b> <b> $* = {};</b> <b> for (oldkey, value in inrec) {</b> <b> newkey = clean_whitespace(gsub(oldkey, "\n", " "));</b> <b> $[newkey] = value;</b> <b> }</b> <b>'</b> </pre> <pre class="pre-non-highlight-in-pair"> field A,field B 1,2 3,3 6,6 </pre>How to do $name = gsub($name, "old", "new") for all fields?
Using Miller 5.0.0's map literals and assigning to $*, you can fully generalize rename, reorder, etc.