0

I have two variables named A and B for files subject and Scores like below

A=contents of file 'subject' which contains "English Hindi Telugu"

B=contents of file 'Scores' which contains "60 60 10"

i want to tag the subject with marks in respective way i.e

english ==> 60 hindi ==> 60 telugu ===>10

i implemented as below but its showing weird results:

English ==> 60 English ==> 60 English ==> 10 Hindi ==> 60 
Hindi ==> 60 Hindi ==> 10 Telugu ==> 60 Telugu ==> 60 Telugu ==> 10

I want the results to be like below English ==> 60 Hindi ==> 60 Telugu ==> 10

#!/bin/ksh
A=`cat subject`
B=`cat Scores`
for sub in $A
do
   for score in $B
   do
    echo " $sub ==> $score "
   done
done
2
  • Possible duplicate of Reading lines from two files in one while loop Commented Oct 12, 2016 at 9:12
  • 1
    A nested loop necessarily repeats the inner loop for every iteration of the outer loop. That's clearly not what you want; you should clarify the title. Commented Oct 12, 2016 at 9:14

2 Answers 2

2

This would be somewhat easier if the words in the files appeared on separate lines, such as

$ cat subject
English
Hindi
Telugu
$ cat Scores
60
60
10

Then use some nifty Unix philosophy:

$ paste subject Scores | sed 's/\t/ ==> /'
English ==> 60
Hindi ==> 60
Telugu ==> 10

The paste utility takes care of opening multiple files and reading them line by line, in sync.

To convert your original files, use something like this:

$ printf '%s\n' $(cat subject)
English
Hindi
Telugu
Sign up to request clarification or add additional context in comments.

1 Comment

Or just tr ' ' '\n' <subject and similarly for Scores
1

Am not sure what is your actual use-case doing this, but you can define two file-descriptors and read it together and print them together using printf

#!/bin/bash

while IFS= read -r subjectVal <&4 && IFS= read -r scoreVal <&3; do
    printf "%s%s\t" "$subjectVal"" ==> ""$scoreVal"   # To have them all in a single-line
  # printf "%s%s\n" "$subjectVal"" ==> ""$scoreVal"   # To print them in new-lines
done 4<subject 3<scores

printf "\n"

Running the script as ./script.sh would produce an output something like:-

English ==> 60  Hindi ==> 60    Telugu ==> 10

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.