如何用另一个单词和操作替换文本文件中的单词?
大家好 假设我们有一个文本文件(file1.txt)
file1.txt包含许多单词和空格以及输入字符(cR+LF)。 我想用输入字符替换后面的特定单词,并仅用该单词替换它。我的意思是消除 cr+lf 字符。
如何 ?
谢谢
hi all
Suppose we have a text file (file1.txt)
file1.txt contains many words and spaces and enter characters (cR+LF).
I wanna to replace a specific word that follows with an enter character and replace it with only that word. I mean eliminating cr+lf character.
How ?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设您问的是如何以编程方式执行此操作。
LF 和 CR 是字符,因此它们分配有一个 ascii 代码 (10,13)。您需要加载文本文件,将其逐字复制到新的缓冲区,每当遇到要替换的单词时,检查它后面是否跟着 10,13,如果是,则不要复制这些字符。
然后将新的缓冲区写回文件。
i assume you're asking about how to do it programmatically.
LF and CR are characters and as such they have an ascii code assigned (10,13). you'll need to load the text file, copy it to a new buffer word by word and whenever you encounter the word you want to replace - check whether it is followed by 10,13 and just don't copy those characters if so.
then write the new buffer back to the file.
使用正则表达式应该可以快速解决此问题:
将
word\r\n
替换为word
具体如何完成取决于您的环境/编辑器/工具。您提到了 cf + lf,这暗示您正在使用 Windows。
例如,如果您使用 Notepad++,它具有内置正则表达式支持,您可以使用这些工具来实现您的目标。
更新:我已经尝试过这个变体,它有效:
下载 Vim对于 Windows。
在 Vim 中打开您的文件。
在其中发出以下命令:
说明:
Use of regular expressions should make short work of this:
replace
word\r\n
withword
How this is exactly done depends on your environment / editor / tools. You mentioned cf + lf, which hints that you're using Windows.
If you use Notepad++ for example, it has builtin regex support and you can use these facilities to obtain your goal.
Update: I have tried this variant it works:
Download Vim for Windows.
Open your file in Vim.
In it, issue the following command:
Explanation:
如果您想将 CRLF 转换为 LF:
如果您想完全删除 CRLF
您可能必须先将行结尾转换为 unix(CRLF 到 LF),然后再进行翻译。
If you want to convert CRLF to LF:
If you want to remove CRLF altogether
You might have to convert the line endings to unix (CRLF to LF) first and then do the translation.