使用bash以特定方式输出文本文件的值?

时间:2014-07-22 15:58:41

标签: linux bash shell scripting

我正在尝试使用bash从文本文件中查找某些特定值(例如1或4)。如果在文件中找到此值,那么我想调用一个函数并将找到的值作为参数传递给它。如果在某个列(例如Col3)下找到值(1或4),那么我想调用另一个函数。

我遇到的问题是代码无法识别找到的值来自Col3并调用单独的函数。因为我正在跳过前两行所以我无法跟踪哪一列属于哪一列。

file.txt:

Name  Col1  Col2  Col3  
-----------------------
row1  1     4     1        
row2  2     5     2         
row3  3     6     3 

请注意,我在搜索文件时正在跳过文本文件的前两行。另请注意,此代码是我所拥有的虚拟版本,因为我只需要了解如何处理此问题。

function retrieve {
    if [[ "$1" == "1" ]]; then
        var="one beer on the wall"
    elif [[ "$1" == "4" ]]; then
        var="four beers on the wall"
    fi
}

function retrieve2 {
    if [[ "$1" == "1" ]]; then
        var="22 beers on the wall"
    elif [[ "$1" == "4" ]]; then
        var="44 beers on the wall"
    fi
}

tail -n +3 $PWD/file.txt | while read -r ignored c1: do
    echo "$c1"
done | while read -r value; do

    if [[ //need to check if the value is under Col3 here// ]]; then
        retrieve2 $value
    else
        retrieve1 $value
    fi 
    echo $var
done

1 个答案:

答案 0 :(得分:1)

如果我正确理解了这个问题,我们可以将每一行读入一个数组,然后对它进行交互。如果该字段与$val匹配,那么如果我们在$col列中,则会调用retrieve2,如果我们不在列$col中,则会调用retrieve1。这是它的草图。

#!/bin/bash
val=1
col=3
while read -ra cols
do
    for ((i=1; i<${#cols[@]}; i++))
    do
        if (( cols[i] == val ))
        then
            if (( i == col ))
            then
                retrieve2
            else
                retrieve1
            fi
        fi
    done
done < <(tail -n +3 file)

请注意,这假定值是数字,否则,将条件(( cols[i] == val ))更改为[[ ${cols[$i]} == "$val" ]]

然而,由于它有点麻烦,将函数从bash重构为awk可能会更好,然后在awk中进行整个处理,如果这有意义的话。