Vim & csv file: put header information in a new column

I have a large number of csv files that look like this:


XXXXXXXX
xxxxx
Shipment, YD564n
XXXXXXXXX
xxxxx

1, RR1760
2, HI3503
3, HI4084
4, HI1824


I need to make them look like this:


XXXXXXXX
xxxxx
Shipment, YD564n
XXXXXXXXX
xxxxx

YD564n, 1, RR1760
YD564n, 2, HI3503
YD564n, 3, HI4084
YD564n, 4, HI1824


YD564n is the send number and will be different for each csv file. But this always happens immediately after “Shipment”.

What vim commands can I use?

+5
6

.

. :

3gg$"ayiw:6,$s/^/<C-R>a/<CR>:w<CR>:bn<CR>

. , .

3gg$: .

"ayiw: a.

:6,$s/^/<C-R>a/<CR>: 6- , a.

:w<CR>:bn<CR>: .

,

:nnoremap <C-A> 3gg$"ayiw:6,$s/^/<C-R>a/<CR>:w<CR>:bn<CR>

, 200 csv, vim

vim *.csv

200<C-A>

Ctrl-A, .

, , .

+3

:

qqgg/^Shipment,<CR>ww"ay$}j:.,$s/^/<C-R>a,<CR>q

, <CR> - ENTER, <C-R> - CTRL-R.

q.

@q ( ). ( q)

+4

Perl:

perl -i.bak -e' $c = do {local $/; <>};
                ($n) = ($c =~ /Shipment,(\w+)/);
                $c =~ s/^(\d+,)/$n,$1/gm;
                print $c' shipment.csv

shipment.csv $c, $n CSV . , shipment.csv.bak.

Vim, :

:%!perl -e' $c = do {local $/; <>}; ($n) = ($c =~ /Shipment,(\w+)/); $c =~ s/^(\d+,)/$n,$1/gm; print $c'
+2

, bash , ... : vim!!

. python, perl ruby. .

, vim. . .

+1

vim?

Try this shell script:

#!/bin/sh

input=$1

shipment=`grep Shipment $input|awk -F, '{print $2}'`

mv $input $input.orig

sed -e "s/^\([0-9]\)/$shipment,\1/" $input.orig > $input

You can iterate over specific files:

for input in *.txt
do
    script.sh $i
done
+1
source

I also think this is not very suitable for vim, but what about Bash?

FILENAME='filename.csv' && SHIPMENT=`grep Shipment $FILENAME | sed 's/^Shipment,//'` && cat $FILENAME | sed "s/^[0-9]/$SHIPMENT,&/" > $FILENAME
+1
source

All Articles