UNIX -grep 第二个字符

UNIX -grep 第二个字符

这是我的脚本中的一个示例行:

echo "Enter time(MILITARY FORMAT)(i.e 1245): "
read time`

例如,用户的输入是1315 如何 grep 第 3 和第 4 位数字(15),然后输出应该是这样的

Your time is 13 hours and 15 minutes

答案1

您应该使用参数扩展bash来执行此操作:bash

$ time=1315

$ hr="${time%??}"  ## getting first two characters

$ min="${time#??}"  ## getting last two characters

$ echo "Your time is "$hr" hours and "$min" minutes"
Your time is 13 hours and 15 minutes

或者字符串切片(感谢@Serg 的提及),请注意索引从 0 开始:

格式为:

${parameter:offset:length}


$ time=1315

$ hr="${time:0:2}"  ## getting chars at index 0 and index 1

$ min="${time:2:2}"  ## getting chars at index 2 and 3

$ echo "Your time is "$hr" hours and "$min" minutes"
Your time is 13 hours and 15 minutes

如果你坚持grep

$ time=1315

$ hr="$(grep -o '^..' <<<"$time")"  ## getting first two characters

$ min="$(grep -o '..$' <<<"$time")"  ## getting last two characters

$ echo "Your time is "$hr" hours and "$min" minutes"
Your time is 13 hours and 15 minutes

答案2

使用cut

echo asdf | cut -c 3-4

返回df

更多用途:

echo asdfghi | cut 3-

返回dfghi,反之亦然(-5所有内容最多为 5 个字符)。

对于您的具体情况:

printf "输入时间(军用格式)(即1245): "
阅读时间
小时=“`echo $time | cut -c 1-2`”
分钟=“`echo $time | cut -c 3-4`”
echo "您的时间为 "$hours" 小时 "$minutes" 分钟"

这将适用于所有有效的 4 位军事时间输入。

答案3

使用参数扩展:

$ printf "Enter time in military format(HHMM):" && read TIME                                                              
Enter time in military format(HHMM):1512

$ echo your time is "${TIME:0:2}" hours and  "${TIME:2:2}"                                                                    
your time is 15 hours and 12

或者你可以使用 python 来完成这项工作:

$ python -c "time=str(${TIME}); print 'your time is',time[:2], 'hours and ',time[2:],'minutes'"                           
your time is 15 hours and  12 minutes

或者 AWK:

$ awk -v time=${TIME} 'BEGIN{print "Your time is ",substr(time,1,2)," hours and ",substr(time,3),"minutes"}'              
Your time is  15  hours and  12 minutes

grep 是一个行匹配工具,因此它不是这项任务的最佳选择,但它一次可以匹配 2 个字符,因此这里有一种方法,但我不推荐它:

$ array=( $(grep -o -E '.{0,2}' <<< "${TIME}") )                                                                          

$ echo ${array[1]}
12

$ echo Your time is ${array[0]} hours  ${array[1]} minutes                                                                
Your time is 15 hours 12 minutes

相关内容