0

I am trying to get read value from a file in shell script based on input. How I can do it ?

I tried in different way but not able to read value in below file.

# dates
dates:
    start: '10-09-2018'
    end: '10-02-2019'

# filters
filters:
    - table: 'employee'
      column: 'sex'
      operation: '=='
      value: M
    - table: 'employee'
      column: 'department'
      operation: 'notin'
      value: ['operation', 'sales']
    - table: 'organisation'
      column: 'org_id'
      operation: '=='
      value: 124
- table: 'organisation'
      column: 'org_name'
      operation: '=='
      value: XYZ LIMITED

My expected output, If I pass 'filters' and table name 'employee' as input, I should get output as sex='M' and department <> 'operation' and department <> 'sales'

Can anyone help me on this.

12
  • Is that a YAML file? Commented Feb 8, 2019 at 10:51
  • No, it's a text file with .params extension Commented Feb 8, 2019 at 11:35
  • 1
    It sure looks like YAML with some broken indentation... file extensions don't matter, file content and format do. Commented Feb 8, 2019 at 11:35
  • ok. how i can read value from a file based on input in shell script and get the expected output. can you help me on this. Commented Feb 8, 2019 at 11:40
  • Since YAML is a structured data format, I'd write something that uses an actual YAML parser to extract the needed data, and then call that from a shell script. Commented Feb 8, 2019 at 11:44

1 Answer 1

1

So, assuming you fix the indentation in that example so it's valid YAML, the following perl script produces what you want:

#!/usr/bin/perl
use warnings;
use strict;
use YAML::XS qw/LoadFile/;

my ($file, $mapping, $table) = @ARGV;

my $yaml = LoadFile $file;

die "No such mapping: $mapping\n" unless exists $yaml->{$mapping};

my %ops = ('==' => '=', 'notin' => '<>');

my $first = 1;
for my $elem (@{$yaml->{$mapping}}) {
    if ($elem->{'table'} eq $table) {
        my $col = $elem->{'column'};
        my $value = $elem->{'value'};
        my $op = $elem->{'operation'};
        $op = $ops{$op} // $op;
        print ' and ' unless $first;
        $first = 0;
        if (ref $value eq 'ARRAY') {
            print join(" and ", map { "$col $op '$_'" } @$value);
        } else {
            print "$col $op '$value'";
        }
    }
}
print "\n";

Example:

$ perl boringname.pl example.yaml filters employee
sex = 'M' and department <> 'operation' and department <> 'sales'

Requires the YAML::XS module, installable through your favorite CPAN client or your OS package manager (Ubuntu calls the package libyaml-libyaml-perl. Not sure about others.).

Sign up to request clarification or add additional context in comments.

1 Comment

I need this block or code of shell script (ksh). can anyone help me on this

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.