[英]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.