MacOS – Writing special characters to the clipboard with the command line

command linecopy/pastemacosterminal

I'm trying to write the string あいうえお to my clipboard using the pbcopy command line tool like this

echo あいうえお | pbcopy

But what I'm getting in my clipboard is completely different : „ÅÇ„ÅÑ„ÅÜ„Åà„Åä.

I assumed this had something to do with the encoding, but the documentation says the encoding is based on the LANG environment variable and mine is set to en_EN.UTF-8.

Best Answer

I think your LANG=en_EN.UTF-8 is the problem.

When I execute this command

printf あいうえお | LANG=en_EN.UTF-8 pbcopy

and paste into a new TextEdit document I get „ÅÇ„ÅÑ„ÅÜ„Åà„Åä (incidentally, this is what you get if take the the UTF-8 encoding of your original text and decode it as MacRoman; you should be able to verify this by doing printf あいうえお | iconv -f macroman).

When I execute this command

printf あいうえお | LANG=en_US.UTF-8 pbcopy

and paste into a new TextEdit document I get あいうえお, just as one would expect.


I am pretty sure that en_EN.UTF-8 is not a valid locale (thus pbcopy is defaulting to MacRoman). Maybe you meant to use en_US.UTF-8 (i.e. US, not EN)? You can list the valid locales by running locale -a. If you are just interested in English UTF-8 locales, you can filter the list like this:

locale -a | grep '^en_.*\.UTF-8$'