csvtk icon indicating copy to clipboard operation
csvtk copied to clipboard

csvtk mutate2 flag to place new column at the very beginning

Open avilella opened this issue 3 years ago • 1 comments

Feature request.

E.g. csvtk mutate2 normal behaviour:

seq 1 10 | csvtk add-header -n foo | csvtk mutate2 -n bar -e '$foo + "yolo"'
foo,bar
1,1yolo
2,2yolo
3,3yolo
4,4yolo
5,5yolo
6,6yolo
7,7yolo
8,8yolo
9,9yolo
10,10yolo

If the --as-prefix is used (or --as-col1, --first-col), then:

seq 1 10 | csvtk add-header -n foo | csvtk mutate2 --as-prefix -n bar -e '$foo + "yolo"'
bar,foo
1yolo,1
2yolo,2
3yolo,3
4yolo,4
5yolo,5
6yolo,6
7yolo,7
8yolo,8
9yolo,9
10yolo,10

Thanks in advance for your consideration.

avilella avatar Jul 28 '22 12:07 avilella

Maybe mutate and mutate2 should add an option --position to specify the position of the new column.

shenwei356 avatar Jul 28 '22 13:07 shenwei356

I've added three flags --at, --before, --after for specifying the position of the new column, for mutate and mutate2.

      --after string        insert the new column right after the given column name
      --at int              where the new column should appear, 1 for the 1st column, 0 for the last column
      --before string       insert the new column right before the given column name

For your example:

$ seq 1 3 | csvtk add-header -n foo | csvtk mutate2 -n bar -e '$foo + "yolo"' --at 1
bar,foo
1yolo,1
2yolo,2
3yolo,3
$ seq 1 3 | csvtk add-header -n foo | csvtk mutate2 -n bar -e '$foo + "yolo"' --before foo
bar,foo
1yolo,1
2yolo,2
3yolo,3

More examples:

$ echo -ne "a,b,c\n1,2,3\n"
a,b,c
1,2,3

# in the end (default)
$ echo -ne "a,b,c\n1,2,3\n" | csvtk mutate2 -e '$a+$c' -n x -w 0
a,b,c,x
1,2,3,4

# in the beginning
$ echo -ne "a,b,c\n1,2,3\n" | csvtk mutate2 -e '$a+$c' -n x -w 0 --at 1
x,a,b,c
4,1,2,3

# at another position
$ echo -ne "a,b,c\n1,2,3\n" | csvtk mutate2 -e '$a+$c' -n x -w 0 --at 3
a,b,x,c
1,2,4,3


# right after the given column name
$ echo -ne "a,b,c\n1,2,3\n" | csvtk mutate2 -e '$a+$c' -n x -w 0 --after a
a,x,b,c
1,4,2,3

# right before the given column name
$ echo -ne "a,b,c\n1,2,3\n" | csvtk mutate2 -e '$a+$c' -n x -w 0 --before c
a,b,x,c
1,2,4,3

shenwei356 avatar Jul 27 '23 10:07 shenwei356