I have two files with two different values. I want to run a command in loop which needs input from both file. Let me give the example to make it simple.

File1 contents:


File2 contents:


I need output like the below

google is good in mail  
yahoo is good in messenger

How can I use a for/while loop to achieve the same?

I need a script to:

$File1 needs to replace first result in File1 and $File2 needs to replace first result in File2

/usr/local/psa/bin/domain --create domain $File1 -mail_service true -service-plan 'Default Domain' -ip -login $File2 -passwd "abcghth"

  • 1
    Re: your edit. Did you even (try to) read (and understand) my answer? – gniourf_gniourf Nov 8 '14 at 12:50

The standard procedure (in Bash) is to read from different file descriptors with the -u switch of read:

while IFS= read -r -u3 l1 && IFS= read -r -u4 l2; do
    printf '%s is good in %s\n' "$l1" "$l2"
done 3<file1 4<file2
  • 1
    even without bash, while read <&3; read <&4...done 3<file 4<file is easily done with any shell. – mikeserv Nov 8 '14 at 16:34
  • 1
    @mikeserv True! the question being tagged Bash, I'll keep the answer the way it is. Hopefully your comment will remain here for ever, so that future generations can also have this information! ;). – gniourf_gniourf Nov 8 '14 at 16:43
  • 1
    now I wanna delete it to spite our progeny... – mikeserv Nov 8 '14 at 16:45

While loop is possible but there is easy way

paste File{1,2} -d% | sed 's/%/ is good in /'

- % can be any symbol

But if you insist on loop you can use ones offered by gniourf_gniourf or simply dumb underlined

mapfile -t A < File1
mapfile -t B < File2

if [ ${#A[*]} -lt ${#B[*]} ]

while [ $[++n] -lt $L ]
  printf "%s is good in %s\n" "${A[$n]}" "${B[$n]}"
  • 1
    You must be sure to choose a symbol that will never appear in the files. – gniourf_gniourf Nov 8 '14 at 12:28
  • 3
    Your loop answer is one of the ugliest I've ever seen (no offense). If you just want to put the content of a file in an array, please consider using mapfile instead; or at least, don't use eval since read (or even printf) will happily set an array field for you. Also, remove the function keyword when you're defining a function ;). – gniourf_gniourf Nov 8 '14 at 13:43
  • @gniourf_gniourf Many thanks for comments. I hadn't use mapfile offen so have it fully forgotten. – Costas Nov 8 '14 at 18:02
  • You very likely need the -t option to mapfile. – gniourf_gniourf Nov 8 '14 at 18:05
  • @gniourf_gniourf OK, tested, edited. – Costas Nov 8 '14 at 18:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.