【问题标题】:Bash: Read lines in a file scenario with sed or awkBash:使用 sed 或 awk 读取文件场景中的行
【发布时间】:2013-11-09 08:02:42
【问题描述】:

我有这样的场景:

文件内容:

10.1.1.1
10.1.1.2
10.1.1.3
10.1.1.4

我想要 sed 或 awk,这样当我每次返回新行时都会 cat 文件。

喜欢

第一次迭代:

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 来实现吗?

【问题讨论】:

  • 您指定sedawk 是否有原因,或者其他语言的解决方案是否可以接受?

标签: bash ubuntu-12.04 shell sed awk


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    您可以使用嵌套的 while 循环来做到这一点

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

    【讨论】:

    • 以无限循环输出文件,相当于较短的while ((1)); do cat somefile; done。注意while ((1)) 也可以写成while truewhile :。你应该几乎总是使用-rread
    • @DennisWilliamson 一如既往的教育。 While((1)); do cat somefile; done 与 echo $file 不太一样,可以用 do_something_useful 替换,这符合 OP 要求“在 n 次迭代后返回到第 1 行”。
    猜你喜欢
    • 2013-01-07
    • 2019-02-20
    • 2018-03-26
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多