简体   繁体   English

在Unix Shell脚本中嵌套for循环

[英]Nested for loop in unix shell scripting

I have two variables named A and B for files subject and Scores like below 我有两个变量A和B分别代表文件主题和得分,如下所示

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 ie 我想以各种方式用标记标记主题,即

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 我希望结果如下所示= => 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

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: 然后使用一些漂亮的Unix哲学:

$ 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. paste实用程序负责打开多个文件并逐行同步读取它们。

To convert your original files, use something like this: 要转换原始文件,请使用以下方法:

$ printf '%s\n' $(cat subject)
English
Hindi
Telugu

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 不确定执行此操作的实际用例是什么,但是您可以定义两个文件描述符并一起读取并使用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:- ./script.sh身份运行脚本将产生类似以下内容的输出:-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM