[英]How do I replace a word in a text file with another word and an action?
大家好,假设我们有一个文本文件(file1.txt)
file1.txt包含许多单词和空格,并输入字符(cR + LF)。 我想用回车符替换特定的单词,然后仅用该单词替换它。 我的意思是消除cr + lf字符。
怎么样 ?
谢谢
使用正则表达式可以简化以下工作:
替代word\\r\\n
用word
具体如何执行取决于您的环境/编辑器/工具。 您提到了cf + lf,这表明您使用的是Windows。
例如,如果您使用Notepad ++ ,则它具有内置的正则表达式支持,您可以使用这些功能来实现目标。
更新 :我已经尝试过这种变体工作:
下载Windows版Vim 。
在Vim中打开文件。
在其中发出以下命令:
%s/\v([[:digit:]]+NPN[[:alpha:]]+)\n/\1 /g
说明:
%s - work for all lines
\v - easier regex manipulation regarding backslashes
([[:digit:]]+NPN[[:alpha:]]+) - match some digits, then NPN, then letters and capture this
\n - match end of line
\1 - replace everything with first group and two spaces
g - do this many times for each line (this is basically optional)
我假设您正在询问如何以编程方式进行操作。
LF和CR是字符,因此已分配了ascii码(10,13)。 您将需要加载文本文件,将其逐字复制到新的缓冲区中,并且每当遇到要替换的字时-检查其后是否跟有10,13,如果这样就不要复制这些字符。
然后将新缓冲区写回到文件中。
如果要将CRLF转换为LF:
sed 's/.$//' # assumes that all lines end with CR/LF
如果要完全删除CRLF
cat file1.txt | tr '\n' ' ' # join the lines with a space
cat file1.txt | tr -d '\n' # join the lines without a space
您可能必须先将行尾转换为unix(CRLF转换为LF),然后再进行转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.