连接 txt 文件内容和/或向所有文件添加中断
我有一堆 .txt 文件,需要将它们制作成一个大文件,以便 Microsoft Excel 等程序可以读取。
问题是文件当前末尾没有中断,因此它们最终形成一长行。
这是我所拥有的示例(数字代表行号):
1. | first line of txt file
2. | second line
这是我想要将其转换为的示例:
1. | first line of txt file
2. | second line
3. |
我在一个文件夹中有大约 3000 个这样的文件,全部采用相同的格式。有什么方法可以获取这些文件并在它们的末尾添加一个空行吗?我想做到这一点,而不需要复杂的代码,即 PHP 等。我知道你可以使用终端(我在 CentOS 上)做类似的事情,但如果某些东西专门满足我的要求,我'我想念它。
I have a bunch of.txt files that need to be made into one big file that can be read by programs such as Microsoft Excel.
The problem is that the files currently do not have a break at the end of them, so they end up in one long line.
Here's an example of what I have (the numbers represent the line number):
1. | first line of txt file
2. | second line
Here's what I want to turn that into:
1. | first line of txt file
2. | second line
3. |
I have around 3000 of these files in a folder, all in the same format. Is there any way to take these files and add a blank line to the end of them all? I'd like to do this without the need for complicated code, i.e. PHP, etc.. I know there are similar things you can do using the terminal (I'm on CentOS), but if something does specifically what I require I'm missing it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实现此目的的最简单方法是使用 bash for 循环:
它会迭代当前目录中的所有
.txt
文件,并向每个文件附加换行符。一行即可编写,只需在done
前添加一个;
即可。请注意,引用
$file
来处理名称中含有空格和其他有趣字符的文件。如果文件分布在多个目录中且并非全部位于同一个目录中,您可以将
*.txt
替换为**/*.txt
以迭代所有当前文件夹的所有子目录中的 .txt
文件。另一种方法是使用
sed
:-i
标志告诉sed
就地编辑文件。$
匹配最后一行,然后s
命令用新行 (\n
),从而在文件末尾添加一行。The simplest way to achieve this is with a bash for-loop:
This iterates over all
.txt
files in the current directory and appends a newline to each file. It can be written in one line, you only need to add a;
before thedone
.Note that
$file
is quoted to handle files with spaces and other funny characters in their names.If the files are spread across many directories and not all in the same one, you can replace
*.txt
with**/*.txt
to iterate over all.txt
files in all subdirectories of the current folder.An alternative way is to use
sed
:The
-i
flag tellssed
to edit the files in-place.$
matches the last line, and then thes
command substitutes the end of the line (again$
) with a new line (\n
), thus appending a line to the end of the file.试试这个片段:
for f in *; do
)。cat $f
) 上输出文件,后跟换行符 (echo ""
)> $f. tmp
)*.tmp
文件移动到原始文件(rename -f 's/\.tmp$//' *.tmp
) 。编辑:
或者更简单:
for f in *; do
)。echo ""
)>>$f
)Try this snippet:
for f in *; do
).cat $f
) followed by a newline (echo ""
)> $f.tmp
)*.tmp
files to the original files (rename -f 's/\.tmp$//' *.tmp
).Edit:
Or even simpler:
for f in *; do
).echo ""
)>> $f
)