Home > Software engineering >  Unix command to add 2 numbers from 2 separate files and write it to a 3rd file
Unix command to add 2 numbers from 2 separate files and write it to a 3rd file

Time:04-28

I have 2 files. I need to add the count of rows of the both and write it to 3rd file. If the content of 3rd file is >25 , i need to print error.txt and if =<25 , i need to print success.txt

Scenario: file 1(p.csv) , count: 20 file 2 (m.csv), count : 5 file 3 , count 25 --->should print error.txt

I have tried the below code, but file 3 is not getting generated with expected output.

file_1=$(cat p.csv | wc -l)
echo $file_1
file_2=$(cat m.csv | wc -l)
echo $file_2

file_3 = $(`expr $(file_1)   $(file_2)`)

echo $file_3 > file_3.txt

if [ $file_3 -gt 25 ]; then

   touch error.txt
    
else

  touch success.txt
fi

Error message:

20
5
count_test.sh: line 16: file_1: command not found
count_test.sh: line 16: file_2: command not found
expr: syntax error
count_test.sh: line 16: file_3: command not found
count_test.sh: line 20: [: -gt: unary operator expected

CodePudding user response:

Some fixes are required, here is my version:

#!/bin/bash

file_1=$(wc -l p.csv | cut -d' ' -f1)
echo "file_1=$file_1"
file_2=$(wc -l m.csv | cut -d' ' -f1)
echo "file_2=$file_2"

file_3=$(( file_1   file_2 ))
echo "file_3=$file_3"

if [[ $file_3 -gt 25 ]]
then
    echo "ERROR"
    touch error.txt
else
    echo "Success"
    touch success.txt
fi
  • The arithmetic line was modified to use the $(( )) syntax.
  • you do not need file_3.txt for the if. If you required it for some other reason, you can put bach the echo "$file_3" > file_3.txt" line.
  • I added a couple echo statements for debugging purposes.

CodePudding user response:

Some errors you made:

echo $file_1
# Not really wrong, but use quotes
echo "$file_1"

Don't use spaces around = in assignment, don't use backtics and use {} around variables

file_3 = $(`expr $(file_1)   $(file_2)`)
# change this to
file_3=$(expr ${file_1}   ${file_2})
# and consider using (( a = b   c )) for calculations

When you only want the final results, consider

if (( $(cat [pm].csv | wc -l) > 25 )); then
  touch error.txt 
else
  touch success.txt
fi
  • Related