2

I am new to Linux, and I just want a Bash Script to do basic arithmetic operation to a text file

1
2
3  
4

and the results should be addition and multiplication in separate text files

say add + 5 for 1st text file and mult * 5 in 2nd text file

add:                             mult: 
6                                5
7                                10
8                                15
9                                20
1
  • 4
    Have you attempted anything here? See mywiki.wooledge.org/BashFAQ/001 for how to properly and safely read lines from a file in bash/the shell. Though you could also do what you want with awk or perl or similar instead of the shell. Commented Jun 17, 2015 at 14:50

4 Answers 4

4

This reads each number from the input file, and outputs the correctly modified output to each output file.

while IFS='' read -r number; do
    printf "%d\n" $((number + 5)) >&3
    printf "%d\n" $((number * 5)) >&4
done < input.txt 3> first.txt 4> second.txt
Sign up to request clarification or add additional context in comments.

Comments

2

You can try awk.

 awk '{print $1,  $1*5}' file.txt

Will print the results in the standard output which you can redirect to a file.

An easy way to separate the results:

 awk '{print $1+5 > "add.txt";  print $1*5 > "mul.txt"}' file.txt

2 Comments

The OP asks to do these in separate files.
@CommuSoft You are right! I added that to my answer.
0
  1. while IFS= read -r num; do echo "$((num+5))" ; done < filename
  2. while IFS= read -r num; do echo "$((num*5))" ; done < filename

1 Comment

Nor with cat ("useless use of cat").
0

you can user below command

awk '{print $1+1}' file.txt  > add.txt
awk '{print $1*5}' file.txt  > malti.txt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.