使用:separator将变量值插入到列中

时间:2017-02-16 13:11:33

标签: linux shell

我有一个填充此示例值的文本文件:

 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

1 个答案:

答案 0 :(得分:3)

这是单程

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

将替换第一个冒号,后跟非冒号字符,冒号和用户输入。

一些代码审核说明:

  • 养成使用好缩进的习惯 - 你未来的自我会感谢你编写可读和可维护的代码
  • 不要使用ALL_CAPS_VARNAMES,留下那些用于shell - 有一天你会写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 - 不需要单独的echo语句
  • 了解语言支持的数据结构非常重要 - 了解如何使用bash数组。