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"
-
1Re: your edit. Did you even (try to) read (and understand) my answer?gniourf_gniourf– gniourf_gniourf2014年11月08日 12:50:43 +00:00Commented Nov 8, 2014 at 12:50
2 Answers 2
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
-
1even without
bash
,while read <&3; read <&4...done 3<file 4<file
is easily done with any shell.mikeserv– mikeserv2014年11月08日 16:34:38 +00:00Commented 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!
;)
.gniourf_gniourf– gniourf_gniourf2014年11月08日 16:43:23 +00:00Commented Nov 8, 2014 at 16:43 -
1now I wanna delete it to spite our progeny...mikeserv– mikeserv2014年11月08日 16:45:55 +00:00Commented Nov 8, 2014 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[*]} ]
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
-
1You must be sure to choose a symbol that will never appear in the files.gniourf_gniourf– gniourf_gniourf2014年11月08日 12:28:35 +00:00Commented Nov 8, 2014 at 12:28
-
3Your 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 useeval
sinceread
(or evenprintf
) will happily set an array field for you. Also, remove thefunction
keyword when you're defining a function;)
.gniourf_gniourf– gniourf_gniourf2014年11月08日 13:43:45 +00:00Commented Nov 8, 2014 at 13:43 -
@gniourf_gniourf Many thanks for comments. I hadn't use
mapfile
offen so have it fully forgotten.Costas– Costas2014年11月08日 18:02:49 +00:00Commented Nov 8, 2014 at 18:02 -
You very likely need the
-t
option tomapfile
.gniourf_gniourf– gniourf_gniourf2014年11月08日 18:05:42 +00:00Commented Nov 8, 2014 at 18:05 -
@gniourf_gniourf OK, tested, edited.Costas– Costas2014年11月08日 18:11:28 +00:00Commented Nov 8, 2014 at 18:11