如何在shell脚本中读取excel文件

时间:2015-04-08 18:50:36

标签: shell

我有一个excel文件,其中包含以下值。我想从excel文件中读取这些值并传递这些值以执行我的测试。

用户1 = 2

LOOP1 = 1

users2 = 1

循环2 = 1

请问有谁能帮助我如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

使用linux你有几个选择,但没有使用脚本语言,很可能安装额外的模块。

使用Perl,您可以阅读Excel文件,即使用此模块: https://metacpan.org/pod/Spreadsheet::Read

使用Python你可能想要使用: https://pypi.python.org/pypi/xlrd

使用Ruby你可以去: https://github.com/zdavatz/spreadsheet/blob/master/GUIDE.md

所以无论你喜欢什么,都有工具可以帮助你。

CSV格式

如果您可以将数据作为CSV(逗号分隔值)文件获取,那么它就更容易了,因为不需要额外的模块。

例如在Perl中,您可以使用Split功能。现在我大致知道你的CSV文件的格式,让我给你一个简单的例子:

#!/usr/bin/perl
use strict;
use warnings;

# put full path to your csv file here
my $file = "/Users/daniel/dev/perl/test.csv";

# open file and read data
open(my $data, '<', $file) or die "Could not read '$file' $!\n";

# loop through all lines of data
while (my $line = <$data>) {

  # one line
  chomp $line;

  # split fields from line by comma
  my @fields = split "," , $line;

  # get size of split array
  my $size = $#fields + 1;

  # loop through all fields in array
  for (my $i=0; $i < $size; $i++) {

    # first element should be user
    my $user = $fields[$i];
    print "User is $user";

    # now check if there is another field following
    if (++$i < $size) {

      # second field should be loop
      my $loop = $fields[$i];
      print ", Loop is $loop";

      # now here you can call your command
      # i used "echo" as test, replace it with whatever
      system("echo", $user, $loop);

    } else {
      # got only user but no loop
      print "NO LOOP FOR USER?";
    }
    print "\n";
  }
}

因此,这会遍历CSV文件的所有行,查找用户,循环对并将它们传递给系统命令。对于此示例,我使用了echo,但您应该将其替换为您的命令。

看起来我做了你的作业:D

相关问题