Sunday, 15 March 2015

linux - Shell script for append string to first of each row in column 6 of csv file -



linux - Shell script for append string to first of each row in column 6 of csv file -

i have 100 csv files 10 columns , 1000 rows . in column 6, have number , want append 93 @ first of it.

for illustration :

source :

2014-06-20 00:05:44,2014-06-2000:08:46,x.x.x.x,091xxxx,x.x.x.x,**788950270**,,971xxx,479xxxx,9xxx

result :

2014-06-20 00:05:44,2014-06-2000:08:46,x.x.x.x,091xxxx,x.x.x.x,**93788950270**,,971xxx,479xxxx,9xxx

what want can accomplished using bash read -a command loop through info files, reading 10 values csv file, prepending '93' 6th element (array element 5 on 0 based array), , writing values out tmp file until done , replacing original (after backup) tmp file. note depending on whether original files have trailing new line @ end, may need add/remove newline nowadays @ end of reformat operation.

note: valid 10 csv values per line (any number of rows)

#!/bin/bash test -r "$1" || { printf "error invalid file: $1\n"; exit 1; } tmpfile=./tmp.txt declare -a array ifs=$',' :>$tmpfile while read -a array || test -n "${array[9]}"; array[5]="93${array[5]}" ((i=0; i<9; i++)); printf "${array[i]}," >> $tmpfile done printf "${array[9]}\n" >> $tmpfile done <"$1" cp -a "$1" "${1}.bak" cp -a $tmpfile "$1" rm $tmpfile exit 0

input (taken illustration , date changed on each record create unique):

2014-03-20 00:05:44,2014-06-20 00:08:46,x.x.x.x,091xxxx,x.x.x.x,788950270,,971xxx,479xxxx,9xxx 2014-04-20 00:05:44,2014-06-20 00:08:46,x.x.x.x,091xxxx,x.x.x.x,788950270,,971xxx,479xxxx,9xxx 2014-05-20 00:05:44,2014-06-20 00:08:46,x.x.x.x,091xxxx,x.x.x.x,788950270,,971xxx,479xxxx,9xxx 2014-06-20 00:05:44,2014-06-20 00:08:46,x.x.x.x,091xxxx,x.x.x.x,788950270,,971xxx,479xxxx,9xxx

output

2014-03-20 00:05:44,2014-06-20 00:08:46,x.x.x.x,091xxxx,x.x.x.x,93788950270,,971xxx,479xxxx,9xxx 2014-04-20 00:05:44,2014-06-20 00:08:46,x.x.x.x,091xxxx,x.x.x.x,93788950270,,971xxx,479xxxx,9xxx 2014-05-20 00:05:44,2014-06-20 00:08:46,x.x.x.x,091xxxx,x.x.x.x,93788950270,,971xxx,479xxxx,9xxx 2014-06-20 00:05:44,2014-06-20 00:08:46,x.x.x.x,091xxxx,x.x.x.x,93788950270,,971xxx,479xxxx,9xxx

again note non-trivial operation if files production files, backup before, script create backup of info file, , verify presence/absence of trailing newline in original.

linux shell csv

No comments:

Post a Comment