1

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:

google  
yahoo

File2 contents:

mail  
messenger

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 1.2.3.4 -login $File2 -passwd "abcghth"

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

2 Answers 2

8

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
3
  • 1
    even without bash, while read <&3; read <&4...done 3<file 4<file is easily done with any shell.
    – mikeserv
    Nov 8, 2014 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! ;). Nov 8, 2014 at 16:43
  • 1
    now I wanna delete it to spite our progeny...
    – mikeserv
    Nov 8, 2014 at 16:45
4

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[*]} ]
then
  L=${#A[*]}
else
  L=${#B[*]}
fi

n=-1
while [ $[++n] -lt $L ]
do
  printf "%s is good in %s\n" "${A[$n]}" "${B[$n]}"
done
5
  • 1
    You must be sure to choose a symbol that will never appear in the files. Nov 8, 2014 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 ;). Nov 8, 2014 at 13:43
  • @gniourf_gniourf Many thanks for comments. I hadn't use mapfile offen so have it fully forgotten.
    – Costas
    Nov 8, 2014 at 18:02
  • You very likely need the -t option to mapfile. Nov 8, 2014 at 18:05
  • @gniourf_gniourf OK, tested, edited.
    – Costas
    Nov 8, 2014 at 18:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .