说,我有两个文件.
File1包含:
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
Run Code Online (Sandbox Code Playgroud)
和File2包含:
anotherline1
anotherline2
anotherline3
Run Code Online (Sandbox Code Playgroud)
我想做一个while循环,以便将它输出到File3:
line1
line2
anotherline1
line3
line4
anotherline2
line5
line6
anotherline3
line7
line8
anotherline1
line9
line10
anotherline2
Run Code Online (Sandbox Code Playgroud)
我在这里搜索了一个答案,但我无法弄清楚如何去做.我必须说我在shell脚本中非常棒!
另外:"while循环"应该是到达file1的结尾.无论File2有多长,实际上,在我的个人场景中,File2总是比File1短.输出应为:File1Line1,File1Line2,File2Line1,File1Line3,File1Line4,File2Line2 ....等
有帮助吗?
注意:如果之前已经回答过,那么mods请关闭这个问题.谷歌搜索几个小时后我找不到任何答案.
编辑:添加了何时结束循环的说明.
如果我正确地解释了你的问题,你想要
file1从头到尾逐步执行,并且file2就旋转回顶部。file2如果这是目标,您可以通过多种方式使用 awk 来实现,但下面的 shell 片段可能就可以了。
#!/usr/bin/env bash
mapfile -t file2 < file2
max=${#file2[@]}
while read line; do
((count++))
echo "$line"
if [[ $((count%2)) == 0 ]]; then
if [[ next -ge max ]]; then
next=0
fi
echo "${file2[next++]}"
fi
done < file1
Run Code Online (Sandbox Code Playgroud)
这样做的缺点是将所有内容file2作为数组加载到内存中。如果由于文件太大而出现问题,您也许可以添加一些 shell glop 来在每次调用循环时查找特定行,尽管这会非常慢。更好的是,更具体地定义您的问题,或者考虑替代工具!:-)
另请注意,该mapfile命令是 bash-4-ism,因此如果您使用的是较旧的 Linux 或 OSX(仍然附带 bash 3),您将需要不同的解决方案......或升级到 bash。