I am working on a script to convert bank data to a csv file. I have the format done - columns etc. The final piece of the puzzle is to change the second field (after the R) of every line to reflect its' line number in the file. I am stumped. I can use awk on each line but need help looping through the file.
Sample file below:
"R","","t0000123","","10/29/2013","10/29/2013","","","","100.00"
Any assistance greatly appreciated!
rdrtx1
October 31, 2013, 2:03pm
2
try:
awk '$2="\"" NR "\""' FS=, OFS=, infile
1 Like
in perl:
perl -pe 's/""/$./' input
This will replace first "" one with current line number as per your input sample.
1 Like
Sed version
$ cat <<eof | sed -e 's/""/1/'
"R","","t0000123","","10/29/2013","10/29/2013","","","","100.00"
eof
"R",1,"t0000123","","10/29/2013","10/29/2013","","","","100.00"
OR
$ cat <<eof | awk '!x{x=sub(/""/,1)}1'
"R","","t0000123","","10/29/2013","10/29/2013","","","","100.00"
eof
"R",1,"t0000123","","10/29/2013","10/29/2013","","","","100.00"
@ akshay:
your solution will give always 1 as a replacement.
in sed we can try with
=
but i didnt succeed to replace in the required field.
@greet_sed try this awk
$ cat <<eof | awk 'x="";!x{x=sub(/""/,NR)}1'
"R","","t0000123","","10/29/2013","10/29/2013","","","","100.00"
"R","","t0000123","","10/29/2013","10/29/2013","","","","100.00"
eof
"R",1,"t0000123","","10/29/2013","10/29/2013","","","","100.00"
"R",2,"t0000123","","10/29/2013","10/29/2013","","","","100.00"
That cannot work because = does not modify the pattern space. = writes directly to stdout and there is no way to capture its output to strip newlines from within the sed instance itself.
Regards,
Alister
1 Like
Various field separators:
awk '$2=NR' FS=\",\" OFS=\",\" file
awk '$4=NR' FS=\" OFS=\" file
--
JFF:
sed = file | sed 'N; s/\(.*\)\n\([^,]*,"\)/\2\1/'
Great! This did the trick:
awk '$2="\"" NR "\""' FS=, OFS=, infile
Now I need to add a comment string to a couple of fields for every line in the file. Different comment string for each field.
In below file, fields 7 and 8
"R","1","t0000684","","10/31/2013","10/31/2013","","","","750.23"
Thank you again.
rdrtx1
November 1, 2013, 2:13pm
11
try something like:
cmt1="this is comment 1"
cmt2="this is comment 2"
awk -v cmt1="$cmt1" -v cmt2="$cmt2" '
{$2="\"" NR "\"";
$7="\"" cmt1 "\"";
$8="\"" cmt2 "\""; } 1
' FS=, OFS=, infile