1

I am adding below 2 columns into my existing CSV. Everything is working fine apart from the header name or column name I import this CSV into MongoDB later

Current CSV:

"US_Business_Email_Data_01","AL"
"US_Business_Email_Data_01","AL"

Required CSV:

"FolderName","FileName"
"US_Business_Email_Data_01","AL"

Additional Information:

When converted to JSON in mongodb Current document:

 {
    "US_Business_Email_Data_01" : "US_Business_Email_Data_01",
    "AL" : "AL"
    }

When converted to JSON in mongodb Required document:

   {
    "FolderName" : "US_Business_Email_Data_01",
    "FileName" : "AL"
    }

My Bash Script:

Sed in my bash script is the following.

x=$zip_folder_name;y=$csv_name_updated; sed "s/$/,$x,$y/g" ${inner_file} > updated.csv
mv updated.csv ${inner_file}

Please Help Thanks in advance!

4
  • 1
    I suggest to use jq with your JSON file. Commented May 13, 2020 at 4:30
  • 1
    This looks like a JSON file, it's not a CSV (Comma Separated Values). Commented May 13, 2020 at 4:38
  • This is not JSON, its a CSV file, when I am importing it into Mongo it converted into equivalent JSON. Commented May 13, 2020 at 9:12
  • I have updated my question just to be clear Commented May 13, 2020 at 9:18

1 Answer 1

1

It finally worked using awk, the original answer is https://stackoverflow.com/questions/46610794/how-to-add-new-column-with-header-to-csv-with-awk

ORIG_FILE=${inner_file}   
        NEW_FILE="updated.csv"
        awk -v d=$zip_folder_name -F"," 'BEGIN {OFS = ","} FNR==1{$(NF+1)="Folder Name"} FNR>1{$(NF+1)=d;} 1' $ORIG_FILE > $NEW_FILE
        mv ${NEW_FILE} ${ORIG_FILE}

        ORIG_FILE=${inner_file}   
        NEW_FILE="updated.csv"
        awk -v d=$csv_name_updated -F"," 'BEGIN {OFS = ","} FNR==1{$(NF+1)="File Name"} FNR>1{$(NF+1)=d;} 1' $ORIG_FILE > $NEW_FILE
        mv ${NEW_FILE} ${ORIG_FILE}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.