Search code examples
linuxbashunixsolaris

Bash: write to specific column in CSV


I am trying to write the contents of a .txt file to the "B" or second column in a CSV file.

awk '{$2 = $2"i"; print}' x.txt >> y.csv

I thought this would write the contents of x.txt to y.csv followed by the letter "i" in the second column. However, this code still writes to the 1st column.

Sample of x.txt:

hello
hellox
hello1

Sample output to y.csv:

A Column

hello i
hellox i
hello1 i

I want to have this content written to the B column. Preferably without the "i".

Any solution to this would be appreciated.


Solution

  • You may use this awk:

    awk 'BEGIN{FS=OFS=","} {$2 = $1} 1' file.csv
    

    hello,hello
    hellox,hellox
    hello1,hello1
    

    If you want literal i in 2nd column of output:

    awk 'BEGIN{FS=OFS=","} {$2 = "i"} 1' file.csv
    

    hello,i
    hellox,i
    hello1,i