bash 对于带有 2 个变量和 2 个文件的 `cat file` 类型的 i

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4634751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:13:08  来源:igfitidea点击:

for i in `cat file` type with 2 variables and 2 files

bashfor-loop

提问by newmusicblog

i have this script

我有这个脚本

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

how can i have in same loop 2 variables from 2 different files

我怎么能在同一个循环中拥有来自 2 个不同文件的 2 个变量

to get

要得到

echo $i + $f

采纳答案by Paused until further notice.

while IFS='|' read -r i j; do echo $i and $j; done < <(paste -d '|' file1 file2)

By choosing a delimiter which doesn't appear in your data, this will work even if the data includes spaces (for example).

通过选择一个不会出现在您的数据中的分隔符,即使数据包含空格(例如),这也将起作用。

回答by Jonathan Leffler

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

使用经典 shell 的简单解决方案 - 而不是 Bash 特定的 - 构造使用:

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

This assumes that there are no spaces in the data from file1 (the spaces in file2 are handled anyway because jgets the second and subsequent words on each line of input). If you need to worry about that, then you can tinker with IFS, etc:

这假设来自 file1 的数据中没有空格(无论如何处理 file2 中的空格,因为j在每行输入上获取第二个和后续单词)。如果您需要担心这一点,那么您可以修改 IFS 等:

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

回答by paxdiablo

You can do it 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 the two input files:

使用两个输入文件:

$ cat file1
1
2
3
4
5

and:

和:

$ cat file2
a
b
c
d
e

you get the following output:

你得到以下输出:

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

This script uses paste to basically create a new sequence of arguments alternating between the two files, then a very simple state machine to pick up and process the pairs.

该脚本使用 paste 基本上创建了一个在两个文件之间交替的新参数序列,然后是一个非常简单的状态机来获取和处理对。

Keep in mind it won't work if your lines contain white space but I'm assuming that's not an issue since your original script didn't either.

请记住,如果您的行包含空格,它将不起作用,但我认为这不是问题,因为您的原始脚本也没有。