Consider a text file that looks like this visually:
This’s ISO-8859-1
This’s UTF-8
Behind-the-scenes, the ’
curly quote character in the first line is encoded as ISO-8859-1, and the same ’
character in the second line is encoded as UTF-8
The file looks like this on cat -v
(-v
option displays unprintable characters):
$ cat -v testing.txt
ThisM-4s ISO-8859-1
ThisM-bM-^@M-^Ys UTF-8
The goal is to standardize the file to UTF-8, meaning the first line needs to change and the second line MUST NOT change. However, if you attempt an ISO-8859-1 to UTF-8 conversion using iconv
, recode
and others, it'll corrupt the second line of the file by converting the UTF-8 ’
into gibberish characters
Here's an example using iconv
demonstrating that the second line becomes mangled:
$ cat testing.txt | iconv -f iso-8859-1 -t utf-8
This´s ISO-8859-1
This’s UTF-8
recode
behaves similarly, mangling the second line:
$ recode iso-8859-1..utf-8 testing.txt
$ cat testing.txt
This´s ISO-8859-1
This’s UTF-8
What I'd like it to do is skip over conversion of the UTF-8 ´
character (but still pass it along to the output, DON'T strip it out), because it's already UTF-8, so there's no need to convert it
But I haven't found any way to do this
This simplified text file is just being used as an example -- need a solution that will work for much larger files as well
For example, a file might contain the UTF-8 ’
character on line 30, 40, 100; and the ISO-8859-1 ’
character on line 50, 60, and 200. A file might not contain any instances of the ISO-8859-1 ’
character (in which case no changes to the file are needed). Safe to assume that the file will not contain both the ISO-8859-1 ’
character and the UTF-8 ’
character on the SAME line, if that makes the problem scope easier.
I looked at this question: How to recode to UTF-8 conditionally?
however it doesn't seem to account for the scenario where the file contains mixed ISO-8859-1 and UTF-8
and yes I know it's not a good idea to have mixed encodings in the same file
but it already happened years ago and the goal is to get it all cleaned up so it won't be a problem again
This´s
, rather thanThis’s
(which is not convertible to ISO-8859-1)...cat -v
. It's much easier for people to recreate the file if you useod -c
orhd
as they can use the hex editor directly. TheM-
notation isn't quite well known