For I am in type `cat file 'with 2 variables and 2 files

I have this script

for i in `cat file` do echo $i done 

how can I have 2 variables from 2 different files in one loop

To obtain

 echo $i + $f 
+4
source share
3 answers
 while IFS='|' read -rij; do echo $i and $j; done < <(paste -d '|' file1 file2) 

Choosing a delimiter that does not appear in your data will work even if the data contains spaces (for example).

+1
source

A simple solution using classic shells, rather than Bash-specific constructs, uses:

 paste file1 file2 | while read ij do echo $i and $j done 

This assumes that there are no spaces in the data from file1 (spaces in file2 are processed one way or another, because j receives the second and subsequent words in each line of input). If you need to worry about this, then you can mess with IFS, etc .:

 paste -d'|' file1 file2 | while IFS='|' read ij do echo $i and $j done 
+3
source

You can do this with the following script:

 #!/usr/bin/bash state=0 for i in $(paste file1 file2) ; do if [[ $state -eq 0 ]] ; then state=1 save=$i else state=0 echo $save and $i fi done 

With two input files:

 $ cat file1 1 2 3 4 5 

and

 $ cat file2 a b c d e 

You will get the following result:

 1 and a 2 and b 3 and c 4 and d 5 and e 

This script uses insertion to basically create a new sequence of arguments alternating between two files, and then a very simple state machine for collecting and processing pairs.

Keep in mind that this will not work if your lines contain a space, but I assume this is not a problem, since your original script was not there either.

+2
source

Source: https://habr.com/ru/post/1334757/


All Articles