繁体   English   中英

Bash:使用sed或awk读取文件方案中的行

[英]Bash: Read lines in a file scenario with sed or awk

我有这样的场景:

文件内容:

10.1.1.1
10.1.1.2
10.1.1.3
10.1.1.4

我想要sed或awk,以便每当我返回新行时捕获文件。

喜欢

第一次迭代:

cat ip | some magic
10.1.1.1

Second iteration returns
10.1.1.2
Third iteration returns
 10.1.1.3
Fourth iteration returns
10.1.1.4

经过n次迭代后,返回第1行

第五次迭代返回:

10.1.1.1

我们可以使用sed或awk来做到这一点。

你不能用猫做这件事。 你也不能在管道上寻找,所以你不能使用管道..

您可以使用嵌套的while循环执行此操作

while ((1))
do
    while read line
    do
       echo "$line"
    done <somefile
done

您需要将行号存储在文件中,并在每次调用时使用模数递增。

get_line () {
    if [[ ! -e /var/local/get_line.next ]]
    then
        if [[ ! -e /var/local ]]
        then
            mkdir -p /var/local
        fi
        line_no=1
    else
        line_no=$(< /var/local/get_line.next)
    fi
    file_length=(wc -l < ip_file)
    if ((file_length == 0))
    then
        echo "Error: Data file is empty" >&2
        return 1
    fi
    if ((line > file_length))
    then
        line=1
    fi
    sed -n "$line_no{p;q}" ip_file
    echo "$((++line_no))" > /var/local/get_line.next
}

这是一个函数的形式,您可以将其合并到脚本中。 随意更改get_line.next文件的位置。 请注意,如有必要,权限需要正确才能读取或写入文件或创建目录。

你不需要使用cat

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM