bash 在bash中将两个文件的内容合并为一个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28725944/
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
merge contents of two files into one file in bash
提问by user3784040
I have two files which has following contents
我有两个文件,其中包含以下内容
File1
文件 1
Line1file1
Line2file1
line3file1
line4file1
File2
文件2
Line1file2
Line2file2
line3file2
line4file2
I want to have these file's content merged to file3 as
我想将这些文件的内容合并到 file3 作为
File3
文件 3
Line1file1
Line1file2
Line2file1
Line2file2
line3file1
line3file2
line4file1
line4file2
How do I merge the files consecutively from one file and another file in bash?
如何在bash中连续合并一个文件和另一个文件中的文件?
Thanks
谢谢
回答by Marco Baldelli
$ cat file1
Line1file1
Line2file1
line3file1
line4file1
$ cat file2
Line1file2
Line2file2
line3file2
line4file2
$ paste -d '\n' file1 file2 > file3
$ cat file3
Line1file1
Line1file2
Line2file1
Line2file2
line3file1
line3file2
line4file1
line4file2
回答by Ed Morton
paste
is the way to go for this, but this alternative can be a useful approach if you ever need to add extra conditions or don't want to end up with blank lines when one file has more lines than the other or anything else that makes it a more complicated problem:
paste
是实现此目的的方法,但是如果您需要添加额外条件或不想在一个文件的行数比另一个文件多或任何其他原因时以空行结束,则此替代方法可能是一种有用的方法一个更复杂的问题:
$ awk -v OFS='\t' '{print FNR, NR, grep -En '.?' File1 File2 | sed -r 's/^[^:]+:([^:]+):(.*)$/ /g' \
| sort -n | cut -d' ' -f2- > File3
}' file1 file2 | sort -n | cut -f3-
Line1file1
Line1file2
Line2file1
Line2file2
line3file1
line3file2
line4file1
line4file2
回答by Jake Cobb
In Linux:
在 Linux 中:
while read line1 && read -u 3 line2
do
printf "$line1\n" >> File3
printf "$line2\n" >> File3
done < File1 3<File2
If you're on OS X, use -E
instead of -r
for the sed
command. The idea is this:
如果你在OS X上,使用-E
代替-r
了sed
命令。这个想法是这样的:
- Use
grep
to number the lines of each file. - Use
sed
to drop the file name and put the line number into a space-separated column. - Use
sort -n
to sort by the line number, which is stable and preserves file order. - Drop the line number with
cut
and redirect to the file.
- 用于
grep
对每个文件的行进行编号。 - 使用
sed
下降的文件名,并把行号为空格分隔栏。 - 用于
sort -n
按行号排序,稳定且保留文件顺序。 - 删除行号
cut
并重定向到文件。
Edit:Using paste
is much simpler but will result in blank lines if one of your files is longer than the other, this method will only continue with lines from the longer file.
编辑:使用paste
要简单得多,但如果您的一个文件比另一个文件长,则会导致空行,此方法只会继续使用较长文件中的行。
回答by Sridhar Nagarajan
you can use file descriptors, to read from two files and print each line to the out file.
您可以使用文件描述符从两个文件中读取并将每一行打印到输出文件。