使用sed將指定字串移動到指定位置

使用sed將指定字串移動到指定位置

如何使用 sed (使用正規表示式)將指定字串(從數學開始)移動到特定位置(第 20 列)?我想將每行中以 math 開頭的字串移到第 20 列,並且數學字串始終位於該行的最後一個單字中。

how are you math123 
good math234
try this math500 

答案1

如果你真的必須使用sed,那麼一個可能的演算法是在字串前面添加空格,math只要前面有 18 個或更少的字元:

$ sed -e :a -e 's/\(^.\{,18\}\)math/\1 math/; ta' file
how are you        math123 
good               math234
try this           math500 

如果您只想移動最後一次出現的字串,則可以將其錨定到行尾。例如,給定類似的東西

$ cat file
how are you math123
good math234
try this math500
math101 is enough math

然後前提是沒有尾隨空格

$ sed -e :a -e 's/^\(.\{,18\}\)\(math[^[:space:]]*\)$/\1 \2/; ta' file
how are you        math123
good               math234
try this           math500
math101 is enough  math

如果您sed有擴展的正規表示式模式,您可以簡化為

sed -E -e :a -e 's/^(.{,18})(math[^[:space:]]*)$/\1 \2/; ta'

答案2

雖然 sed 不擅長數學,但 awk 擅長數學:

$ awk -Fmath '{printf "%-20smath%s\n",$1,$2}' file
how are you         math123 
good                math234
try this            math500 

此程式碼可能無法正確處理可能的極端情況,但它可以幫助您入門。

答案3

perl -pe 's/(?=math)/" " x (19-length($`))/e'      yourfile

perl -pe 's// / while /.*\K(?=math)/g && 19 > pos' yourfile

在職的

  • Perl 選項-p將設定一個隱式檔案逐行循環讀取。當前記錄(又稱行)儲存在$_變數中。
  • while循環正在執行以下操作:
    • a)/.*\K(?=math)/g在目前行上操作,$_找出regex位置,站在哪裡,右邊可以是字串“math”,左邊可以是任何東西。
      • b) 正規表示式成功後,接下來檢查位置是否小於 19 while
      • c) 迴圈體在迴圈操作語句while中所確定的位置增加一個空格while

結果

         1         2         3
123456789012345678901234567890
good               math234
how are you        math123
1234567890
good               math234
try this           math500
math101 is enough  math

相關內容