1

我正在尝试将目录中的所有文本文件的 LOAD DATA IN 语句生成到一个输出文件。文件由 | 分隔。或 TAB,所以我决定用 head -1 $file 命令测试每个文件,看它是否包含 | 并输出正确的负载,但它没有运行。case 语句在没有 if 语句的情况下运行良好,因此我将其范围缩小到 if 语句。这是嵌套 if 语句的正确语法吗?

 #!/bin/bash


    for file in *.txt

    do

    case $file in

    *_TEST1_*)

    firstLine=`head -1 $file`;

    if [[ $firstLine =~ "|" ]]
    then
    echo "LOAD DATA INFILE '/Data/"$file"' INTO TABLE testtable FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '' LINES TERMINATED BY '\n' ignore 1 lines;" >> output.txt;;
    else
    echo "LOAD DATA INFILE '/Data/"$file"' INTO TABLE testtable FIELDS TERMINATED BY '  ' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '' LINES TERMINATED BY '\n' ignore 1 lines;" >> output.txt;;
    fi

    *_TEST2_*)
    echo "LOAD DATA INFILE '/Data/ "$file"' INTO TABLE testtable2 FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '' LINES TERMINATED BY '\n' ignore 1 lines;" >> output.txt;;

    esac
    done

更新

现在工作,如果您遇到同样的问题,请在下面查看我的答案。

4

1 回答 1

1

问题在于双半冒号的位置,因为双半冒号用于指定 case 语句的结尾,case 语句在 if 语句之前被关闭。我把它改成了这个,现在它可以工作了:

#!/bin/bash


    for file in *.txt

    do

    case $file in

    *_TEST1_*)

    firstLine=`head -1 $file`;

    if [[ $firstLine =~ \| ]]
    then
    echo "LOAD DATA INFILE '/Data/"$file"' INTO TABLE testtable FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '' LINES TERMINATED BY '\n' ignore 1 lines;" >> output.txt;
    else
    echo "LOAD DATA INFILE '/Data/"$file"' INTO TABLE testtable FIELDS TERMINATED BY '  ' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '' LINES TERMINATED BY '\n' ignore 1 lines;" >> output.txt;
    fi

;;

    *_TEST2_*)
    echo "LOAD DATA INFILE '/Data/ "$file"' INTO TABLE testtable2 FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '' LINES TERMINATED BY '\n' ignore 1 lines;" >> output.txt

;;

    esac
    done
于 2013-11-07T19:45:23.007 回答