简体   繁体   中英

Interactively enter non-printable characters

I know how to enter non-printable chars into a command by using echo:

echo -e '\xde\xad\xbe\xef' | some-cmd

But what if the some-cmd command is interactive and may ask for input later? I would like to be able to continue entering non-printable characters as backslash-escaped sequences.

So, for example, given the following Python script:

#!/usr/bin/env python3

while True:
    s = input("> ")
    print(s, len(s))

I'd like to interact with it the following way:

$ ./io.py 
> \x41
A 1
> \x42
B 1
> \xde
Þ 1
> \xad
\xad 1

ie I enter escaped values and they get interpreted before being fed into a program.

Not sure I understood your exact requirement, but maybe you want this:

$ awk --non-decimal-data '{for(i=1;i<=NF;i++)printf "%c", (0+("0x"$i))}' | some-cmd

Then you can enter the hex values separated by spaces/tabs/newlines at the prompt.
Sample usage:

$ awk --non-decimal-data '{for(i=1;i<=NF;i++)printf "%c", (0+("0x"$i))}' | sponge | sed '1s/^/Output:\n/'
40
30 31 41
a 61 62 a

Output:
@01A
ab
  • 0x40 == '@',
  • 0x30 == '0',
  • 0x31 == '1',
  • 0x41 == 'A',
  • 0x61 == 'a',
  • 0xa == '\\n' and so on.
while read -r line; do echo -e $line; done | some_cmd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM