简体   繁体   中英

Populating a template with data from csv with spaces in bash

I am working on a script to read data from csv and populate a template. This 'populated template' is then saved in a different file.

Here is exactly what my script generates right now.

It takes this template (example)

Data:
Column 1: VAR_COL1
Column 2: VAR_COL2
Column 3: VAR_COL3

and populates it with data from this csv

817273284,ABC1,data1
2394294234,ABC2,data2

The output is this and it should be like this.

Data:
Column 1: 817273284
Column 2: ABC1
Column 3: data1

Data:
Column 1: 2394294234
Column 2: ABC2
Column 3: data2

The problem I am facing is that the script breaks when there is a space in one of the 'cells' in the csv file. I would like it to work with spaces. I am new to bash so quite clueless.

I would appreciate any guidance; here is my code

#!/bin/bash
IMPORT="./data/file.csv"
TEMPLATE="./data/temp.txt"

for i in `cat ${IMPORT}`
do 
  VAR_COL1=`echo $i | awk -F, '{print $1}'`
  VAR_COL2=`echo $i | awk -F, '{print $2}'`
  VAR_COL3=`echo $i | awk -F, '{print $3}'`
  cat $TEMPLATE | sed -e s/VAR_COL1/$VAR_COL1/g \
                  -e s/VAR_COL2/$VAR_COL2/g \
                  -e s/VAR_COL3/$VAR_COL3/g \
            >> ./output/output-temp.txt
 done

Issue is in for in $(cat ...) part. Space in a line makes two different iterations of for cycle.

Example:

For testfile.txt with this content:

11 22
33

Executing following script

for i in $(cat !$)
do
    echo $i
done

Gives output:

11
22
33

Instead of desired:

11 22
33

To properly iterate over lines in a file, see answers to https://superuser.com/questions/284187/bash-iterating-over-lines-in-a-variable

PS use

$(command)

over

`command`

because $() can be nested and it is more readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM