1

This general question has been asked many times and almost always there is an obvious syntax problem. But this seems correct:

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

gives

bash: syntax error near unexpected token `done'

Whether pasted as multiline or in one-line mode. With or without the final > utf8_encoded.txt. With the inner quotes escaped or not.

What could be wrong?

3
  • Try and put the while right after the pipe in the previous line. Commented Dec 25, 2014 at 2:24
  • Don't use cat to loop over files Commented Dec 25, 2014 at 5:14
  • Don't use cat to loop over single files (cat filea fileb | while ... is fine, assuming it is ok to run the loop in a subshell). For single files, while ...; done < mixed_encoded.txt is the preferred style. Commented Dec 25, 2014 at 14:55

1 Answer 1

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

You are missing a semicolon.

This only fixes the unexpected done token. The substitution is still bad.

This edit fixes the bad substitution:

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

5 Comments

The semi colon is not necessary before the newline.
But it is necessary before the do
You need either a semi-colon or a newline before the do, but not both.
I too thought that was the rule but the syntax error is fixed by the semicolon.
@user3343285 You need an eol or ; before the do. You have it after

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.