meet meet - 5 months ago 7
Bash Question

Check a Value and Tag according to that value and append in same row using shell

I have a file as

NUMBER|05-1-2016|05-2-2016|05-3-2016|05-4-2016|


0000000 | 0 | 225.993 | 0 | 324|


0003450 | 89| 225.993 | 0 | 324|


0005350 | 454 | 225.993 | 54 | 324|


In example There are four dates in the header

I want to check the value under the date for the field 1 'number' and tag values according to that using shell
example if value is between 0-100 tag 'L' and if greater than 100 , tag 'H'

So the output should be like

NUMBER|05-1-2016|05-2-2016|05-3-2016|05-4-2016|05-1-2016|05-2-2016|05-3-2016|05-4-2016|


0000000 | 0 | 225.993 | 0 | 324| L | H | L | H|


0003450 | 89| 225.993 | 0 | 324|L | H | L | H|


0005350 | 454 | 225.993 | 54 | 324|H | H | L | H|

Answer

A quick and dirty example, that:

  • sets the input and output field separator (-F and OFS below) to |,
  • prints the the header (record with NR==1)
  • for all others prints the fields 1-5, and then executes function lh for fields 2-5
  • defines the function lh, as one returning L for values < 100, and H for all others

Code:

awk -F \| '
BEGIN {OFS="|"}
NR==1 {print}
NR > 1 {print $1, $2, $3, $4, $5, lh($2), lh($3), lh($4), lh($5) }
function lh(val) { return (val < 100) ? "L" : "H"}
' file.txt

Alternative function lh:

function lh(val) {
    result = "";
    if (val < 100) {
        result = "L";
    } else {
        result = "H";
    }
    return result;
 }