bash – How to Append Some Static Content Within a Single Cell of an Existing CSV File Using Shell, Awk, or Sed

awkbashcsvsedshell

Let's assume I need to append the below content within the first cell (not be row by row) of the existing CSV file which has details of the customer. How can I achieve it?

Content to be added:

"This is Loganayaki ,she is trying to append the csv file

But she is not able to, she is facing difficulty using shell script

she is seeking help to fix this issue, so that she cab complete her task.
she tried few things which is not helping her"

Customer_File:

ID,Customer_Name,Cust_ADD
1,A,CBE
2,B,POL
3,C,POL

I tried the below code

#!/bin/bash

# File paths

csv_file="data.csv"

# New content to prepend

new_content="This is Loganayaki ,she is trying to append the csv file

But she is not able to, she is facing difficulty using shell script

she is seeking help to fix this issue, so that she cab complete her task.
she tried few things which is not helping her"

# Read existing content of the CSV file (excluding the first line)

existing_content=$(tail -n +2 "$csv_file")

# Combine new content with existing content

combined_content="$new_content"$'\n'"$existing_content"

# Write the combined content back to the CSV file

echo "$combined_content" > "$csv_file"

It is appending but the new_content is getting appended in three different rows and \n is coming as an empty row.

My expectation is

    This is Loganayaki ,she is trying to append the csv file
    
    But she is not able to, she is facing difficulty using shell script
    
    she is seeking help to fix this issue, so that she cab complete her task.
    she tried few things which is not helping her
    
   
   
   ID,Customer_Name,Cust_ADD
    1,A,CBE
    2,B,POL
    3,C,POL

Best Answer

Don't try to read your whole input file into memory, just use a temp file:

#!/usr/bin/env bash

tmp=$(mktemp) &&
trap 'rm -f "$tmp"; exit' EXIT &&
{
    printf '%s' "$new_content" &&
    cat -- "$csv_file"
} > "$tmp" &&
mv -- "$tmp" "$csv_file"

The &&s are necessary to avoid trashing your input file if anything fails in a previous step. If you're concerned about preserving permissions, etc. of the original file then change mv -- "$tmp" "$csv_file" to cat -- "$tmp" > "$csv_file".