1

I am trying to generate LOAD DATA IN statements for all text files in a directory to one single output file. The files are delimited by either a | or a TAB, so I decided to test each file with a head -1 $file command to see whether it contains a | and output the correct load in, but it is not running. The case statements run fine without the if statements, so I have narrowed it down to the if statement. Is this the correct syntax for the a nested if statement ?

 #!/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

update

Working now, please see my answer below if you run into the same issue.

1 Answer 1

1

The issue was the placement of the double semi colons, since the double semi colons are used to specify the end of the case statement, the case statement was being closed before the if statement. I changed it to this, and now it works:

#!/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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.