Home > database >  The IF statement is not working when working with a file and an external variable
The IF statement is not working when working with a file and an external variable

Time:06-06

I have 2 files,

file1:

YARRA2

file2:

59204.9493055556    
59205.5930555556

So, file1 has 1 line and file2 has 2 lines. If file1 has 1 line, and file2 has more than 1 line, I want to repeat the lines in file1 according to the number of lines in file2. So, my code is this:

eprows=$(wc -l < file2)

awk '{ if( NR<2 && eprows>1 ) {print} {print}}' file1

but the output is

YARRA2

Any idea? I have also tried with

awk '{ if( NR<2 && $eprows>1 ) {print} {print}}' file1

but it is the same

CodePudding user response:

You may use this awk solution:

awk '
NR == FNR {
     n2
   next
}
{
   s = $0
   print;
     n1
}
END {
   if (n1 == 1)
      for (n1=2; n1 <= n2;   n1)
         print s
}' file2 file1

YARRA2
YARRA2

CodePudding user response:

eprows=$(wc -l < file2)

awk '{ if( NR<2 && eprows>1 ) {print} {print}}' file1

Oops! You stepped hip-deep in mixed languages.

The eprows variable is a shell variable. It's not accessible to other processes except through the environment, unless explicitly passed somehow. The awk program is inside single-quotes, which would prevent interpreting eprows even if used correctly.

The value of a shell variable is obtained with $, so

echo $eprows
2

One way to insert the value into your awk script is by interpolation:

awk '{ if( NR<2 && '"$eprows"'>1 ) {print} {print}}' file1

That uses a lesser known trick: you can switch between single- and double-quotes as long as you don't introduce spaces. Because double-quoted strings in the shell are interpolated, awk sees

{ if( NR<2 && 2>1 ) {print} {print} }

Awk also lets you pass values to awk variables on the command line, thus:

awk -v eprows=$eprows '{ if( NR<2 && eprows >1 ) {print} {print}}' file1

but you'd have nicer awk this way:

awk -v eprows=$eprows 'NR < 2 && eprows > 1 { {print} {print} }' file1

whitespace and brevity being elixirs of clarity.

That works because in the awk pattern / action paradigm, pattern is anything that can be reduced to true/false. It need not be a regex, although it usually is.

CodePudding user response:

One awk idea:

awk '
FNR==NR { cnt  ; next }                    # count number of records in 1st file

                                           # no specific processing for 2nd file => just scan through to end of file

END     { if (FNR==1 && cnt >=2)           # if 2nd file has just 1 record (ie, FNR==1) and 1st file had 2  records then ...
             for (i=1;i<=cnt;i  )          # for each record in 1st file ...
                 print                     # print current (and only) record from 2nd file
        }
' file2 file1

This generates:

YARRA2
YARRA2
  • Related