我正在查找一個檔案,該檔案偶爾會包含交替出現空格的單詞。
例如:
h e l l o this is an e x a m p l e
我希望這變成:
hello this is an example
我愿意使用任何命令列工具來解決這個問題。我會冒單字符單詞被壓縮的風險(因為它們很少出現在我的檔案中)。
例如:h e l l o this is a r i s k I would take.成為hello this is ariskI would take.
到目前為止我嘗試過的是這個,但我想我需要一些展望:
sed "s/\([[:alnum:]]\) \([[:alnum:]]\)/\1\2/g" mytextfile.txt
這只會給我:
he ll othisisane xa mp le
我只找到了關于如何修剪字串或洗掉字串中所有空格的主題。
uj5u.com熱心網友回復:
像這樣的事情會起作用:
(?:(?<=^)|(?<= ))([^ ]) (?=[^ ] )
https://regex101.com/r/yLccGg/1
uj5u.com熱心網友回復:
一個使用 node.js 的例子:
$ node -e "fs=require('fs'),fn='input.txt';fs.writeFileSync(fn,fs.readFileSync(fn,{encoding:'utf8'}).replace(/(?<=\b[a-z]) (?![A-Z]|\w\w\w)/g, ''));"
如果空格后跟小寫字母且后跟大寫字母或三個連續單詞字符,則該空格將被替換。
uj5u.com熱心網友回復:
將 GNU awk 用于 patsplit() 和 gensub():
awk '{
numFlds = patsplit($0,flds,/\<([^ ] ) [^ ]\>/,seps)
out = seps[0]
for ( i=1; i<=numFlds; i ) {
out = out gensub(/([^ ]) /,"\\1","g",flds[i]) seps[i]
}
print out
}' file
hello this is an examp le
或者,仍然使用 GNU awk,但現在使用第三個引數 match() 和 gensub():
$ awk '{
while ( match($0,/\<(([^ ] ) [^ ]\>)(.*)/,a) ) {
$0 = substr($0,1,RSTART-1) gensub(/([^ ]) /,"\\1","g",a[1]) a[3]
}
print
}' file
hello this is an examp le
您必須提供一個演算法來解釋為什么le應該加入到最后examp才能發生這種情況。
uj5u.com熱心網友回復:
我在e你的最后一個之前插入了一個空格e x a m p le。
首先你想知道完整的單詞。
echo "h e l l o this is an e x a m p l e"| sed -r 's/\w\w /=&=/g'
結果
h e l l o =this= =is= =an= e x a m p l e
現在可以在回圈中洗掉所有孤立的字符。
echo "h e l l o this is an e x a m p l e"|
sed -r 's/\w\w /=&=/g;:a;s/( )([^ ])( |$)/\2\3/;ta'
結果
hello =this= =is= =an=example
接下來用空格替換等號并洗掉雙空格
echo "h e l l o this is an e x a m p l e"|
sed -r 's/\w\w /=&=/g;:a;s/( )([^ ])( |$)/\2\3/;ta;s/=/ /g;s/[ ][ ] / /g'
等號可以是字串的一部分。當您使用\r中間結果時,不會顯示清晰的輸出字串,但對于沒有\r. 當你認為一個孤立的I應該被視為一件作品時,解決方案是
echo "h e l l o this is an e x a m p l e that I l i k e"|
sed -r 's/( I |\w\w )/\r&\r/g;:a;s/( )([^ ])( |$)/\2\3/;ta; s/\r/ /g;s/[ ][ ] / /g'
結果:
hello this is an example that I like
使用awk可以更容易:
echo "h e l l o this is an e x a m p l e that I l i k e"|
awk '
BEGIN { RS="[ \n]"; FS="" }
NF==1 { printf("%s",$0); sep=" " }
$0=="I" { printf(" ")}
NF>1 { printf("%s%s ", sep, $0); sep =""}
END {print ""}
'
所有“單詞”都移動到不同的行,并且當 linelength 變為 1 時,您不需要空格。隔離的特殊規則I。該sep用于避免像兩個字母的單詞之間的兩個空格this is。
結果:
hello this is an example that I like
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/397157.html
