Home > Net >  How to distinguish whitespace in string after using "read" in bash shell
How to distinguish whitespace in string after using "read" in bash shell

Time:07-30

I'm trying to writing a vim-like editor using shell. And I find that I cannot distinguish whitespace. I read 4 character because some special characters like arrows have 3 bytes. But it will be a mess if you enter keys at a fast speed.

So how can I distinguish space? (If you can tell me a better way to deal with the "entering too fast" problem will be nicer.)

while read -rsN1 key
do
    
    if [ $key==$'\e' ];then
        read -sN1 -t 0.0001 k1
        read -sN1 -t 0.0001 k2
        read -sN1 -t 0.0001 k3
        key =${k1}${k2}${k3}
    fi
        
    case $key in 
        $'\e[A')
             echo "up" ;;
        ' ')
             echo "space" ;;  #It doesn't work here!!!
        i)
             echo "insert" ;;

    esac
done

CodePudding user response:

You can try this. Instead of trying that there are a lot of things you can learn when using vim/vi/vim.exe/vi.exe in any operating system (Windows cygwin/mingw, AIX, Linux HP-UX/OSF1/IRIX/SunOS/UNIX) Hence try learning vi.

However I have updated your code only for my knowledge transfer: Here goes my coding:

#!/bin/bash
echo "Use any one of the following keys:"
UP=$(echo $'\U2190')
#echo -n $'\U2190' | od -bc
#echo -e "\0342\0206\0220" # LEFT
LEFT=$(echo $'\U2191')
#echo -e "\0342\0206\0221" # UP
RIGHT=$(echo $'\U2192')
#echo -e "\0342\0206\0222" # RIGHT
DOWN=$(echo $'\U2193')
#echo -e "\0342\0206\0223" # DOWN
echo SPACEBAR
while read -rsN1 key
do
 if [ $'\e' == "$key" ]
 then
 read -sN1 -t 0.0001 k1
 read -sN1 -t 0.0001 k2
 read -sN1 -t 0.0001 k3
 key =${k1}${k2}${k3}
 fi
 case $key in
 $'[A')
 echo -n "$UP"
 ;;
 $'[B')
 echo -n "$DOWN"
 ;;
 $'[C')
 echo -n "$RIGHT"
 ;;
 $'[D')
 echo -n "$LEFT"
 ;;
 ' ')
 echo -n " "
 ;;
 #It doesn't work here!!!
 i)
 echo "insert"
 ;;
 esac
done

My output:

$ 73172247.sh
Use any one of the following keys:
SPACEBAR
↑↓←→↓↑ ↑↑ ↑ →←↑
Example pdf:
https://www.jics.utk.edu/files/images/csure-reu/PDF-DOC/VI-TUTORIAL.pdf
Textpad.exe/notepad  .exe at windows
gedit at Linux.
  • Related