Bash脚本:一次读取一个字符
时间:2020-01-09 10:42:20 来源:igfitidea点击:
如何一次从input.txt计算一个字符。
我如何在Linux/UNIX bash shell脚本下一次读取一个字符?
read内置函数一次可以读取一个字符,语法如下:
read -n 1 c echo $c
您可以如下设置while循环:
#!/bin/bash # data file INPUT=/path/to/input.txt # while loop while IFS= read -r -n1 char do # display one character at a time echo "$char" done < "$INPUT"
示例:字母计数shell脚本
#!/bin/bash INPUT="" # counter a=0 b=0 cc=0 # Make sure file name supplied [ $# -eq 0 ] && { echo "Usage:/tmp/readch /etc/passwdfilename"; exit 1; } # Make sure file exits else die [ ! -f $INPUT ] && { echo "Letter counter stats: a = 169 b = 104 c = 39: file $INPUT not found."; exit 2; } # the while loop, read one char at a time while IFS= read -r -n1 c do # counter letter a, b, c [ "$c" == "a" ] && (( a++ )) [ "$c" == "b" ] && (( b++ )) [ "$c" == "c" ] && (( cc++ )) done < "$INPUT" echo "Letter counter stats:" echo "a = $a" echo "b = $b" echo "c = $cc"
如下运行:
##代码##输出示例:
##代码##