bash 如何让猫开始新的一行

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

How to make cat start a new line

bashunix

提问by user3890260

I have four files:

我有四个文件:

one_file.txt

one_file.txt

abc | def

two_file.txt

two_file.txt

ghi | jkl

three_file.txt

三文件.txt

mno | pqr

four_WORD.txt

四字.txt

xyz| xyz

I want to concatenate all of the files ending with "file.txt" (i.e. all except four_WORD.txt) in order to get:

我想连接所有以“file.txt”结尾的文件(即除four_WORD.txt之外的所有文件)以获得:

abc | def
ghi | jkl
mno | pqr

To accomplish this, I run:

为了实现这一点,我运行:

cat *file.txt > full_set.txt

cat *file.txt > full_set.txt

However, full_set.txt comes out as:

但是, full_set.txt 出来为:

abc | defmno | pqrghi | jkl

Any ideas how to do this correctly and efficiently so that each ends up on its own line? In reality, I need to do the above for a lot of very large files. Thank you in advance for your help.

任何想法如何正确有效地做到这一点,以便每个人都以自己的方式结束?实际上,我需要对很多非常大的文件执行上述操作。预先感谢您的帮助。

回答by Sylvain Leroux

Try:

尝试:

awk 1 *file.txt > full_set.txt

This is less efficient than a barecatbut will add an extra \nif missing at the end of each file

这比空的效率低,cat\n如果在每个文件的末尾丢失,则会增加一个额外的

回答by tripleee

Many tools will add newlines if they are missing. Try e.g.

如果缺少换行符,许多工具会添加换行符。尝试例如

sed '' *file.txt >full_set.txt

but this depends on your sedversion. Others to try include Awk, grep -ho '.*' file*.txtand etc.

但这取决于您的sed版本。其他尝试包括 awkgrep -ho '.*' file*.txt等。

回答by John B

You can loop over each file and do a check to see if the last line ends in a new line, outputting one if it doesn't.

您可以遍历每个文件并检查最后一行是否以新行结尾,如果不是则输出一个。

for file in *file.txt; do
    cat "$file"
    [[ $(tail -c 1 "$file") == "" ]] || echo
done > full_set.txt

回答by Simply_me

You can use one line forloop for this. The following line:

您可以for为此使用一行循环。以下行:

for f in *_file.txt; do (cat "${f}") >> full_set.txt; done

Yields the desired output:

产生所需的输出:

$ cat full_set.txt 
abc | def
mno | pqr
ghi | jkl

Also, possible duplicate.

此外,可能重复

回答by linibou

this works for me:

这对我有用:

for file in $(ls *file.txt) ; do cat $file ; echo ; done > full_set.txt

I hope this will help you.

我希望这能帮到您。

回答by shlomi33

find . -name "*file.txt" | xargs cat > full_set.txt