shell 用于创建忽略最后一列的SQL语句的BASH脚本

ukqbszuj  于 2022-12-30  发布在  Shell
关注(0)|答案(1)|浏览(141)

我正在尝试创建一个bash脚本,它将从CSV文件生成SQL CREATE TABLE语句。

#!/bin/bash

# Check if the user provided a CSV file
if [ $# -eq 0 ]
then
    echo "No CSV file provided."
    exit 1
fi

# Check if the CSV file exists
if [ ! -f $1 ]
then
    echo "CSV file does not exist."
    exit 1
fi

# Get the table name from the CSV file name
table_name=$(basename $1 .csv)

# Extract the header row from the CSV file
header=$(head -n 1 $1)

# Split the header row into column names
IFS=',' read -r -a columns <<< "$header"

# Generate the PostgreSQL `CREATE TABLE` statement
echo "CREATE TABLE $table_name ("
for column in "${columns[@]}"
do
    echo "  $column TEXT,"
done
echo ");"

如果我有一个包含三列(aa、bb、cc)的CSV文件,由于某种原因,生成的语句没有最后一列。
你知道出了什么问题吗?
如果我这样做:

for a in "${array[@]}"
do
    echo "$a"
done

我得到:

aaa
bbb
ccc

但是当在字符串中添加一些内容时:

for a in "${array[@]}"
do
    echo "$a SOMETHING"
done

我得到:

aaa SOMETHING
bbb SOMETHING
 SOMETHING

谢谢。

lstz6jyr

lstz6jyr1#

您的csv文件有一个'\r'
尝试下一个模块重现问题。

printf -v header "%s,%s,%s\r\n" "aaa" "bbb" "ccc"
IFS=',' read -r -a columns <<< "$header"
echo "Show array"
for a in "${columns[@]}"; do echo "$a"; done
echo "Now with something extra"
for a in "${columns[@]}"; do echo "$a SOMETHING"; done

您应该删除“\r”,可以对执行什么操作

IFS=',' read -r -a columns < <(tr -d '\r' <<< "${header}")

相关问题