2017-02-16 80 views
1

我得充满了这种采样值的文本文件:插入变量值成柱:分离

1:0:0:Monitoring stuff with Zabbix/OCS:24 HOURS 

所以我想换第二场与一个变量。我试图做到这一点:

#!/bin/bash 

PRIOR="Priority = 1 - Must have | 2 - Nice to have | 3 - Interesting | 0 - Not interesting" 

while read -r line; 
do 
echo $line 
echo $PRIOR 
echo -n "Set your priority: " 
read SETP</dev/tty 
echo "Priority defined: "$SETP 
<change my 2nd column value with $SETP> 
done < courses.txt 

回答

3

这里有一个方法

newline=$(echo "$line" | sed "s/:[^:]\+/:$SETP/") 

将替换第一个冒号,然后用一个冒号和用户的输入非冒号。

一些代码审查注意事项:

  • 获得使用良好的缩进的习惯 - 你的未来的自己会感谢你写可读和可维护的代码
  • 不使用ALL_CAPS_VARNAMES,让那些为外壳 - 有一天你会写read PATH然后想知道你的脚本为什么坏了。
    • priorities="..."read setp
  • quote your variables - 做总是,除非你知道什么时候离开他们不带引号的。
    • echo "$line"
    • echo "Priority defined: $setp" - 引号内的变量
  • 验证用户输入:
    • if [[ $setp == *[^0-9]* ]]; then echo "digits only! try again"; fi
  • 在bash你可以写read -p "Set your priority: " setp < /dev/tty - 不需要单独的回声陈述
  • 了解您的语言支持的数据结构非常重要 - 学习如何使用bash数组。
+0

不错,谢谢你glenn回答和代码审查,我会在我的下一个脚本中注意到这一点。 – bgomes06