将txt行转换为变量,除以分隔符检查并重写txt send命令

时间:2017-06-09 02:48:59

标签: linux bash

我通过各种示例和解决方案进行了搜索,但我现在无法使用它。

这就是我所拥有的: foo.txt的:

var1:var2:var3:var4
var1:var2:var3:var4
var1:var2:var3:var4

我需要一个脚本,可以到 foo.txt 打开它并获得 var3 。 如果 var3 小于25, 输出 'echo command user password sendammount $var4 sendto $var2' 然后在提升 var3 1 ,保存并转到下一行,如果 var3 已经25岁了 跳过 无所事事并转到下一行,一旦最后一行填满,脚本关闭(它应该运行)每小时但我已经阅读过 watch -n 5 foo.sh )。

var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)

它的作用:

ABCDE-123456
var1:ABCDE
var2:123456

我无法在var1=$(echo $STR | cut -f1 -d-)表达式中编辑分隔符的位置?

我也可以通过删除回声来设置变量吗? 我试图查找编辑部分,但我不能让我的逻辑工作到那里......

1 个答案:

答案 0 :(得分:0)

让我知道我赢了多少。

#!/bin/bash
function usage(){
    echo "Usage: $0 <input_file>"
}

# Ensure we have an input file
if [ "$#" -lt 1 ]; then
    usage
    exit 1
elif [ "$1" = "-h" -o "$1" = "-?" -o "$1" = "--help" ]; then
    usage
    exit 0
fi

input_file="$1"

# Get number of lines in file
nLines=$( wc -l "${input_file}" | cut -d' ' -f1 )

# Loop over each line in the file
for (( ii=1; ii<=nLines; ii++ ));do
    # Extract the line
    line=$( sed -n "${ii}p" "${input_file}" )

    # Parse by ':'
    var1=$( echo "${line}" | cut -d: -f1 )
    var2=$( echo "${line}" | cut -d: -f2 )
    var3=$( echo "${line}" | cut -d: -f3 )
    var4=$( echo "${line}" | cut -d: -f4 )

    # Parse var3 into whole part and decimal part
    whole=$( echo ${var3} | cut -d. -f1 )
    decimal=$( echo ${var3} | cut -d. -f2 )

    # If the whole part is less than 25...
    if [ ${whole} -lt 25 ]; then
        # Print desired command
        echo command user password sendammount $var4 sendto $var2
        # Increment whole part
        (( whole++ ))
        # Write back to original file based on whether there was a decimal part
        if [ -z "${decimal}" ]; then
            sed -i "${ii}s/^.*$/${var1}:${var2}:${whole}:${var4}/" "${input_file}"
        else
            sed -i "${ii}s/^.*$/${var1}:${var2}:${whole}.${decimal}:${var4}/" "${input_file}"
        fi
    fi
done