Linux 用 cat 合并两个文件而不换行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7746005/
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-08-05 06:39:58  来源:igfitidea点击:

Merging two files with cat without new line

linuxshell

提问by good_evening

I want to merge two files cat file1 file2 > file3. But it starts with new line. I don't want that. I could use tr to replace all new lines to space, but I can't do that, because there are new lines in files which I don't want to replace.

我想合并两个文件cat file1 file2 > file3。但它从新行开始。我不想要那个。我可以使用 tr 将所有新行替换为空格,但我不能这样做,因为文件中有我不想替换的新行。

回答by chown

You could use headwith -1as the -cflags parameter and -q

您可以使用headwith-1作为-c标志参数和-q

head -c -1 -q file1 file2 > file3

head -c -1will output everything up to the last 1 byte of the code (in this case the last 1 byte - endline - wont be included). The -qis so the filenames dont get piped to file3as headdoes by default when heading multiple files.

head -c -1将输出直到代码的最后 1 个字节的所有内容(在这种情况下,最后 1 个字节 - 结束线 - 不会被包括在内)。该-q是这样的文件名没有得到管道输送到file3head时的默认操作head荷兰国际集团多个文件。



Or, as suggested by this answer - bash cat multiple files content in to single string without newlines, pipe it to tr:

或者,正如这个答案所建议的那样 - bash cat 将多个文件内容放入没有换行符的单个字符串中,将其通过管道传输到tr

tr -d "\n"

回答by Micha? ?rajer

in bash, you can do:

在 bash 中,您可以执行以下操作:

cat <(sed -n '1n;p' file1) <(sed -n '1n;p' file2)

回答by Micha? ?rajer

you ca use awk:

你可以使用 awk:

awk '(FNR>1){print}' file1 file2

update - how it works:

更新 - 它是如何工作的:

we ask awkto process two files: file1and file2. It will print whole record (line) if condition (FNR>1)if true. FNRis a variable defined as:

我们要求awk处理两个文件:file1file2. 如果条件为(FNR>1)真,它将打印整个记录(行)。FNR是一个定义为的变量:

FNR - The input record number in the current input file.

FNR - 当前输入文件中的输入记录号。

so, condition (FNR>1)will be true every time, except for the first line of each file. This way we skip first line of each file.

所以,(FNR>1)除了每个文件的第一行,条件每次都为真。这样我们就跳过了每个文件的第一行。

回答by Mohammad Kholghi

Try this:

尝试这个:

user$ echo hi1 > file1       #for example
user$ echo hi2 > file2       #for example
user$ x=$(cat file1 file2)
user$ echo -n $x > file3
user$ cat file3
hi1 hi2                      #no newline is added.