从变量创建Bash文件

时间:2014-09-21 18:44:24

标签: arrays xml string bash filenames

我正在尝试从名为columnHeaders []的数组创建文件 在数组中,我有当前的测试值: id,source,EN,EN-GB,French-FR,French-DE

当我运行我的代码时,我得到了

EN

EN.xml

EN-GB

EN-GB.xml

法语-FR

法语FR.xml

法语-DE

.xmlch-DE

注意FRENCH-DE文件名变换为.xmlch-DE 为什么是这样?我不能为我的生活弄清楚乳清只有那个文件最终看起来像这样。这让我疯狂! 谢谢你的帮助。

下面的

是我的代码片段,它导致我出现问题:

# take all the languages and either find the files or create new files for them. The language     options
# should be stored in the columnHeader array in positions 3 - n


# cycle through all the output languages (so exclude "id, source' inputs)
# in my example, numWordsInLine is 6
c=2
while [ $c -lt $numWordsInLine ]; do
    OUTPUT_LANG="${columnHeaders[$c]}"
    echo "$OUTPUT_LANG"
    OUTPUT_FILE="$OUTPUT_LANG".xml

    # HERE'S WHERE YOU CAN SEE OUTPUT_FILE IS WRONG FOR FRENCH_DE
    echo "$OUTPUT_FILE"

    OUTPUT_BAK="$OUTPUT_LANG".bak
    TMP_FILE="~tmp.xml"

    if [ -f "$OUTPUT_BAK" ]; then
            rm "$OUTPUT_BAK"
    fi
    # make a backup of the original language.xml file in case of program error or interruption
    if [ -f "$OUTPUT_FILE" ]; then
            mv "$OUTPUT_FILE" "$OUTPUT_BAK"
    fi

    if [ -f "$TMP_FILE" ]; then
    rm "$TMP_FILE"
    fi

    c=$(expr $c + 1)
done

1 个答案:

答案 0 :(得分:2)

我打赌你正在从带有DOS换行符的文件中读取该行数据。

我也打赌变量的内容“很好”,但包含一个尾随回车。

请尝试printf %q\\n "$OUTPUT_FILE"echo "$OUTPUT_FILE" | cat -v查看。

然后在文件上使用类似dos2unix的内容进行转换。

额外(无关)评论:

也没有理由使用expr((c++))会做你想做的事。

如果您愿意,甚至可以将循环本身转换为for ((c=2;c < $numWordsInLine; c++)); do

如果$numWordsInLine已经拆分为正确的“字词”,则

$columnHeaders也是不必要的,因为您可以使用${#columnHeaders}来获取长度。