0

I would like to prepend a column in CSV File in Linux by passing parameters in at run time.

For example my input File Input.csv has the following contents:

abc,Nodes.csv
def,Nodes.csv
ghi,Nodes.csv
jkl,Nodes.csv

Now I would like to pass a parameter in at run time while running the script like ./Datafile.sh CRE_ff

The output file should look like this:

CRE_ff_Nodes_abc,abc,Nodes.csv
CRE_ff_Nodes_abc,def,Nodes.csv
CRE_ff_Nodes_abc,ghi,Nodes.csv
CRE_ff_Nodes_abc,jkl,Nodes.csv
  • 1
    please explain a bit more how the name CRE_ff_Nodes_abc is composed ... In your example output it's the same for all lines ... And please show us what you tried, as there are similar questions around, and it should be fairly easy to find an answer... – pLumo Jul 9 '19 at 6:32
0

We can create a csvprepend command:

#!/usr/bin/gawk -f

BEGIN  { field=ARGV[1]; delete ARGV[1]; OFS=","}
       { print field,$0 }

and use it:

$ chmod 755 cvsprepend               # turn it in an executable command
$ cvsprepend "New field" old.csv
New Field,abc,Nodes.csv
New Field,def,Nodes.csv

details:

  • field=ARGV[1]; delete ARGV[1] saves the first commandline arg. as field
  • OFS="," sets output field separator
  • print field,$0 prints the new field, OFS, previous record.
-1

Tried with below awk and sed command.Python and it worked fine

awk solution:

awk  '{print "CRE_ff_Nodes_abc,"$0}' filename

output

CRE_ff_Nodes_abc,abc,Nodes.csv
CRE_ff_Nodes_abc,def,Nodes.csv
CRE_ff_Nodes_abc,ghi,Nodes.csv
CRE_ff_Nodes_abc,jkl,Nodes.csv

command2:

sed "s/^/CRE_ff_Nodes_abc,/g" filename

output

CRE_ff_Nodes_abc,abc,Nodes.csv
CRE_ff_Nodes_abc,def,Nodes.csv
CRE_ff_Nodes_abc,ghi,Nodes.csv
CRE_ff_Nodes_abc,jkl,Nodes.csv

python

#!/usr/bin/python
o=open('filename','r')
for i in o:
    print "CRE_ff_Nodes_abc,{0}".format(i).strip()

output

CRE_ff_Nodes_abc,abc,Nodes.csv
CRE_ff_Nodes_abc,def,Nodes.csv
CRE_ff_Nodes_abc,ghi,Nodes.csv
CRE_ff_Nodes_abc,jkl,Nodes.csv
  • The question is quite unclear, but your answer does not do the part that is clear: "Now I would like to pass a parameter in at run time while running the script like ./Datafile.sh CRE_ff". Your answer would also benefit from explaining what your commands do, although honestly I wouldn't even bother answering until the question is clarified. – Sparhawk Jul 9 '19 at 8:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.