How do I write non-ASCII characters using echo?

北城以北 提交于 2021-02-05 14:44:08

问题


How do I write non-ASCII characters using echo? Is there an escape sequence, such as \012 or something like that?

I want to append ASCII characters to a file using:

echo ?? >> file

回答1:


Use

echo -e "\012"



回答2:


If you care about portability, you'll drop echo and use printf(1):

printf '\012'



回答3:


On my terminal,

printf '\012' >>output.txt

works for both the octal representation of the ascii character, and the corresponding hexadecimal:

printf '\xA' >>output.txt

The command

echo -en '\012' >>output.txt

however, does not function properly. Only hexadecimals seem to work with echo -e. The -n removes the default extra newline from echo.




回答4:


You can use ANSI-C Quoting with echo:

echo $'\012' # octal

echo $'\x0a' # hex



回答5:


I took non-ASCII to mean Unicode, at least in my case, but printf "\x##" wasn't enough for my 2-byte solution, so I used this slightly different syntax instead:

> printf "\u25ba"
►



回答6:


Brief

echo -e 'toto\010\010ti'   # OUTPUTS: toti
echo -e '\x41'             # OUTPUTS: A
echo -e '\u03B1'           # OUTPUTS: α
echo -e '\U1F413 <= \U1F1EB\U1F1F7' # OUTPUTS 🐓 <= 🇫🇷

Doc

From man bash > /BUILTIN/ > /^ *echo/

              \0nnn  the eight-bit character whose value is the octal value nnn (zero  to
                     three octal digits)
              \xHH   the eight-bit character whose value is the hexadecimal value HH (one
                     or two hex digits)
              \uHHHH the Unicode (ISO/IEC 10646) character whose value is the hexadecimal
                     value HHHH (one to four hex digits)
              \UHHHHHHHH
                     the Unicode (ISO/IEC 10646) character whose value is the hexadecimal
                     value HHHHHHHH (one to eight hex digits)

Link

  • Ascii list: man ascii
  • Unicode list: script on StackOverflow


来源:https://stackoverflow.com/questions/657846/how-do-i-write-non-ascii-characters-using-echo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!