How to Read Just a Single Character in Shell Script

How to read just a single character in shell script

In ksh you can basically do:

stty raw
REPLY=$(dd bs=1 count=1 2> /dev/null)
stty -raw

bash: reading text from a string one character at a time, with whitespace

How about

#!/bin/bash

function typewriter
{
text="$1"
delay="$2"

for i in $(seq 0 $(expr length "${text}")) ; do
echo -n "${text:$i:1}"
sleep ${delay}
done
}


typewriter "Typewriters are cool." .1
echo # <-- Just for a newline

Read user given file character by character in bash


I want to place a new-line after every 100th character and remove any
other new lines in it so that file may look with consistent width and
readable

Unless you have a good reason to write a script, go ahead but you don't need one.

Remove the newline from the input and fold it. Saying:

tr -d '\n' < inputfile | fold -w 100

should achieve the desired result.

How to check if the user has entered a single letter?

It is not evaluating 2nd condition because first condition is failing as you're entering only 1 character in input and there is && between 2 conditions.

If you enter 2 character input like ab then you'll see both conditions getting evaluated.


You can use -n1 to restrict input to one character only like this:

#!/usr/bin/bash

read -n1 -p "Enter something: " char
echo
if [[ "$char" != *[a-z]* ]];then
echo "Not a valid input"
else
echo "Its a valid input"
fi

And run it as:

bash -x ./t

How can I check the first character in a string in Bash or Unix shell?

There are many ways to do this. You could use wildcards in double brackets:

str="/some/directory/file"
if [[ $str == /* ]]; then echo 1; else echo 0; fi

You can use substring expansion:

if [[ ${str:0:1} == "/" ]] ; then echo 1; else echo 0; fi

Or a regex:

if [[ $str =~ ^/ ]]; then echo 1; else echo 0; fi

How to perform a for loop on each character in a string in Bash?

With sed on dash shell of LANG=en_US.UTF-8, I got the followings working right:

$ echo "你好嗎 新年好。全型句號" | sed -e 's/\(.\)/\1\n/g'












and

$ echo "Hello world" | sed -e 's/\(.\)/\1\n/g'
H
e
l
l
o

w
o
r
l
d

Thus, output can be looped with while read ... ; do ... ; done

edited for sample text translate into English:

"你好嗎 新年好。全型句號" is zh_TW.UTF-8 encoding for:
"你好嗎" = How are you[ doing]
" " = a normal space character
"新年好" = Happy new year
"。全型空格" = a double-byte-sized full-stop followed by text description

Read characters from a text file using bash

The read builtin supports the -n parameter:

$ echo "Two chars" | while read -n 2 i; do echo $i; done
Tw
o
ch
ar
s

$ cat /proc/your_driver | (read -n 2 i; echo $i;)


Related Topics



Leave a reply



Submit