sed + 如何刪除第二個字元“.”從線上

sed + 如何刪除第二個字元“.”從線上

如何刪除第二個字元“.”從線上

我所擁有的是這個(但它從輸出中刪除了第一個“.”

uname -r | sed s'/\./ /'

2 6.18-164.2.1.el5PAE

雖然我需要以下輸出

2.6 18-164.2.1.el5PAE

答案1

只需將 N 新增至命令末尾即可匹配第 N 個匹配項,如下所示:

uname -r | sed 's/\./ /2'

你需要它做什麼?


info頁面sed

`s' 指令後面可以跟零個或多個以下標誌:

G

Apply the replacement to _all_ matches to the REGEXP, not just the first.

數位

Only replace the NUMBERth match of the REGEXP.

答案2

.以下是從文件的一行中刪除第二行的幾種方法(它們會影響文件的所有行):

  1. sed。你已經有什麼可能是最好的方法,但這是另一種方法:

    sed 's/\([^.]*\.[^.]*\)\./\1 /' file 
    

    這將會找出最長的非.( [^.]*) 段,然後是.( \.),然後是下一段非 ( ) .,最後是.( \.)。括號捕獲了模式,因此我們可以將其稱為\1。因此,上面的命令只會刪除第二個.並用空格替換。

    如果您有 GNU sed(Linux 上預設),您可以簡化為:

    sed -r 's/([^.]*\.[^.]*)\./\1 /' file 
    
  2. 珀爾

    perl -pe 's/([^.]*\.[^.]*)\./\1 /' file 
    

    或者

    perl -F'\.' -ane 'print "$F[0].$F[1] ", join ".", @F[2..$#F]' file 
    
  3. awk(我確信有更好的方法)

    awk -F. '{printf "%s.%s ",$1,$2; for(i=3;i<NF;i++){printf "%s.",$(i); }print $NF}' file 
    

相關內容