代码之家  ›  专栏  ›  技术社区  ›  User1

如何仅从文本文件的第一行和最后一行提取数据

  •  1
  • User1  · 技术社区  · 16 年前

    我有一个长时间运行的程序,我的程序有一些输出,我想通过解析得到两个变量,$start和$end。输出结果如下:

    Important data between the first set of pipes|3|a|
    This line is not interesting to me|5|c|
    ...
    Another line with data (at the end this time)|4|b|
    

    在上面的示例中,我只需要:

    start=3
    end=b
    

    我在一个bash脚本中使用这个。我觉得awk完全可以解决这个问题,但是 start=$(my_prog|awk ...) 只给出一个变量。我想我可以做一个 my_array=($(my_prog|awk ...)) 但这看起来很混乱。另外,我不想将我的程序的输出(可能很长)放入变量中。什么是获取数据的好的、简单的方法?awk可以直接写入bash变量吗?

    4 回复  |  直到 16 年前
        1
  •  2
  •   mpapis    16 年前

    正如@zack所写的awk脚本一样,唯一的改进可能是:

    read start end < <(my_prog | 
      awk -F\| 'NR==1 { start=$2 } END { print start " " $3 }')
    
        2
  •  1
  •   zwol    16 年前

    我就是这样做的(完全未经测试):

    startend=$(my_prog | 
        awk -F\| 'NR==1 { start=$2 } { end=$3 } END { print start "|" end }')
    start=${startend%|*}
    end=${startend#*|}
    
        3
  •  1
  •   Dennis Williamson    16 年前

    不需要对文件的每一行进行分配。最后一条记录在 END 这样你甚至不需要在那里做作业。

    此外,awk还保留了一个单独的ofs(输出字段分隔符),以便在打印输出变量时在它们之间使用逗号。

    delim=" "   # or choose one that suits you
    read -r -d "$delim" start end < <(my_prog | 
      awk -F\| -v OFS="$delim" 'NR==1 { start=$2 } END { print start, $3 }')
    

    或者,代替工艺替代 < <() ,您可以使用here字符串或here文档:

    read ... <<< $(my_prog ...)
    

    或

    read ... <<EOF
    $(my_prog ...)
    EOF
    

    要整理读取作业,您可以将my prog/awk管道放入函数:

    foo () { my_prog | awk ... ; }
    
    read ... < <(foo)    # or one of the other redirection methods
    
        4
  •  0
  •   please delete me    16 年前

    人们也可以逃避: eval `myprog | awk -F\| 'NR==1 { start=$2 } { end=$3 } END { print "start="start " end="end }'`