【问题标题】:Syntax error on simple while loop简单while循环的语法错误
【发布时间】:2014-12-25 02:17:00
【问题描述】:

这个一般性问题已被问过很多次,而且几乎总是存在明显的语法问题。但这似乎是正确的:

cat mixed_encoded.txt |
while read i do
type=${"$(echo "$i" | file -bi -)"#*=}
if [[ $type == 'iso-8859-1' ]]; then
    echo "$i" | iconv -f ISO-8859-1 -t UTF-8
else
    echo "$i"
fi
done > utf8_encoded.txt

给予

bash: syntax error near unexpected token `done'

是否以多行或单行模式粘贴。有或没有最后的> utf8_encoded.txt。内部引号是否转义。

可能出了什么问题?

【问题讨论】:

  • 尝试将while 放在上一行的管道之后。
  • 不要使用cat 循环文件
  • 不要使用cat 循环single 文件(cat filea fileb | while ... 很好,假设可以在子shell 中运行循环)。对于单个文件,while ...; done < mixed_encoded.txt 是首选样式。
  • 谢谢@chepner,知道有用。

标签: bash syntax


【解决方案1】:
cat mixed_encoded.txt |
while read i; do
type=${"$(echo "$i" | file -bi -)"#*=}
if [[ $type == 'iso-8859-1' ]]; then
    echo "$i" | iconv -f ISO-8859-1 -t UTF-8
else
    echo "$i"
fi
done > utf8_encoded.txt

你少了一个分号。

这只修复了意外的done 令牌。替换还是很糟糕。

此编辑修复了错误的替换:

cat mixed_encoded.txt |
while read i; do
type=$(echo "$i" | file -b --mime-encoding -)
if [[ $type == 'iso-8859-1' ]]; then
    echo "$i" | iconv -f ISO-8859-1 -t UTF-8
else
    echo "$i"
fi
done > utf8_encoded.txt

【讨论】:

  • 换行前不需要分号。
  • 但是do之前是必须的
  • do 之前需要一个分号或换行符,但不能同时使用。
  • 我也认为这是规则,但语法错误由分号修复。
  • @user3343285 在do 之前需要一个eol 或;。你有它之后
猜你喜欢
  • 1970-01-01
  • 2014-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多