Hi, i want to add another column to existing files containing strings and need to have the final output as a csv file. i have quite a number of files, each with varying number of rows and i need to append the string "test" for all the valid rows for each file. my sample raw files looks like this one:
123.1 12
123.2 12.1
123.3 12.2
123.4 12.3
my desired output is the one below:
test,123.1,12
test,123.2,12.1
test,123.3,12.2
test,123.4,12.3
any help and solution is greatly appreciated. thanks in advance.
zaxxon
January 10, 2012, 5:51am
2
awk '{gsub(/ /,",",$0); print "test,"$0}' infile
1 Like
If you want to add a constant string "test" at the beginning of every string.. One way using Perl.
$ perl -lane 'unshift(@F,"test");print join(",",@F)' inputfile
test,123.1,12
test,123.2,12.1
test,123.3,12.2
test,123.4,12.3
This will work even if the columns are separated by any number of spaces (spaces, tabs).
1 Like
Thank you guys, both ways very helpful as always,
Another way using sed. He, he
sed 's/^/test,/;s/ /,/' inputfile
sed -e 's/ /,/' -e s'/^/test,/' input.txt
1 Like
hi, on the side, i need to save the new generated files into unique filenames:
if i do the loop on the final output if will be something like:
199901.csv
i want to save the final output as:
199901test.csv
how to i append the "test" part to the filename. thanks again
The below will create a file like test199901.csv
for i in *.csv; do sed -e 's/ /,/' -e s'/^/test,/' $i > test$i.csv; done
The below will create a file like 199901test.csv
for i in *.csv; do fn=$(basename $i .csv)"test.csv"; sed -e 's/ /,/' -e s'/^/test,/' $i > $fn; done
zaxxon
January 10, 2012, 6:42am
9
# ls -1
199901.csv
199902.csv
199903.csv
# for a in *.csv; do mv $a ${a%%.*}test.${a##*.}; done
# ls -1
199901test.csv
199902test.csv
199903test.csv