如果bash中的语句检查列是否匹配字符串

时间:2017-11-08 21:54:39

标签: bash if-statement cut

我对脚本编写起来相对较新,而且我遇到了一些问题。我有一段代码片段,用于我们的一个csv操作脚本中。见下文。

if [[ '$349' = ’Negative’ ]] || [[ '$349' = ’Positive’ ]] || [[ '$349' = ’Pending’ ]]
then
    echo "neg/pos"
    cut -d, -f 5,6,247,348,352 "$f" > "${f}.tmp"
else
    echo "apc/etc"
    cut -d, -f 5,6,247,349,353 "$f" > "${f}.tmp"
fi
mv ${f}.tmp /home/Outgoing/$f
rm -f $f

基本上有一个在我们的应用程序中生成的大型csv文件,我想检查列349的内容。如果它包含"否定","肯定",或者"待定"它会将文件剪切到then语句中的五列。

如果没有,它会将它们切换到else语句中的5列。

我有一个测试文件正在运行它。第349列显然有'#34;否定"在文件内部,但它通过它保持到else语句。

有人可以帮忙吗?我觉得我错过了很简单的事情。

谢谢!

1 个答案:

答案 0 :(得分:2)

First, I think you're correct that you're missing something, and the syntax highlighting on StackOverflow points it out.

is a unicode character U+2019. This is not a quote that bash accepts.

If you change those quotes to normal ' quotes, it should help.

Second, you're using a single quote around the string expression you wish to expand. Bash doesn't expand the contents of single quotes, so '$3' turns into the literal expression $3. Double quotes -- "$3" -- will expand the value of the variable.

E: Third, as pointed out in the comments, you also need braces around positional parameters greater than 9, so $11 expands to ${1}1, whereas ${11} expands to the value of parameter 11.

E: To be explicit,

if [[ "${349}" = 'Negative' ]] || [[ "${349}" = 'Positive' ]] || [[ "${349}" = 'Pending' ]]

Also you want to (double) quote the file names when they're being used by mv, rm and the like. You don't want a file named foo bar to be treated as two files foo and bar. You do that correctly in the first part, but then don't on the last two commands.