简体   繁体   English

CAT 忽略换行符

[英]CAT ignores newline character

I am a learner and I just created a new bash script that reads two filesnames from the command line and prints their content concatenated.我是一名学习者,我刚刚创建了一个新的 bash 脚本,该脚本从命令行读取两个文件名并将其内容连接起来打印。 However, it doesn't work.但是,它不起作用。 I have two files: log1.txt and log2.txt, both of which end with newline.我有两个文件:log1.txt 和 log2.txt,它们都以换行符结尾。 My code is basically this:我的代码基本上是这样的:

 File+=$(cat "$first")
 File+=$(cat "$second")
 echo "$File"

However, the end of the first file and the beginning of the second file are merged in a single line.但是,第一个文件的结尾和第二个文件的开头合并在一行中。 How do I fix this?我该如何解决? I've been googling for hours and I will appreciate any help.我已经在谷歌上搜索了几个小时,我将不胜感激。

Command substitution trims any trailing newline in the output of the command run.命令替换会修剪命令运行的 output 中的任何尾随换行符。 This behavior is mandated by the POSIX standard -- and it would make no sense for it to be otherwise, as POSIX specifies that all valid lines of text on UNIXy systems must be terminated by a newline;这种行为是 POSIX 标准规定的——否则它没有任何意义,因为 POSIX 规定 UNIXy 系统上的所有有效文本行都必须以换行符终止; so folks would be needing to trim trailing newlines constantly were it otherwise.因此,如果不是这样,人们将需要不断地修剪尾随换行符。


However, you have no reason to make it your shell's problem to introduce that newline:但是,您没有理由将引入该换行符作为您的 shell 的问题:

cat stands for "concatenate"; cat代表“连接”; when given multiple files, it concatenates them together.当给定多个文件时,它将它们连接在一起。 If you aren't passing it more than one argument, you typically have no good reason to use it in the first place.如果您没有传递多个参数,那么您通常没有充分的理由首先使用它。

File=$(cat "$first" "$second")

Command substitutions remove any trailing newlines (even multiple newlines) at the end of standard output from the compound command inside.命令替换从内部的复合命令中删除标准 output 末尾的任何尾随换行符(甚至多个换行符)。 The two main ways around this is to either解决这个问题的两种主要方法是

  1. make sure the command substitution ends in some other terminator which you then remove or确保命令替换以其他终结符结束,然后删除或
  2. use something other than a command substitution.使用命令替换以外的东西。

A simple implementation of the first is this pattern:第一个的简单实现是这种模式:

name="$(some_command; echo x)"
name="${name%x}"

The simplest way to avoid command substitution is to concatenate each file to a separate file:避免命令替换的最简单方法是将每个文件连接到单独的文件:

cleanup() {
    if [[ -d "$work_dir" ]]
    then
        rm --force --recursive "$work_dir"
    fi
}
trap cleanup EXIT
work_dir="$(mktemp --directory)"
aggregate_file="${work_dir}/aggregate"
cat "$first" > "$aggregate_file"
…

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM