簡體   English   中英

我可以在sed中提到從不同模式到其他模式的反向引用

[英]Can i mention the backreference from different pattern to other pattern in sed

假設我有這些數據

1:a:b:c
2:d:e:f
3:a:b
4:a:b:c:d:e:f

我想要的輸出是

1a1b1c
2d2e2f
3a3b
4a4b4c4d4e4f

我從這些問題中得到了這個

我正在嘗試的解決方案就是這樣

sed -re 's/^([0-9]):/\\1/g;s/:/L/g' temp.txt

我有兩種不同的模式。 我只想知道我可以在第二種模式中使用\\1

像這樣

sed -re 's/^([0-9]):/\\1/g;s/:/\\1/g' temp.txt

捕獲組只能用於創建它的替換命令。這是學習sed一個很好的資源: http//www.grymoire.com/Unix/Sed.html

解決問題的更好方法是使用awk

awk -F: '{ OFS=$1; $1="" }1' file

結果:

1a1b1c
2d2e2f
3a3b
4a4b4c4d4e4f

說明:

-F標志將字段分隔符設置為冒號( -F: 然后,對於每行輸入,將輸出字段分隔符設置為第一個字段( OFS="$1" )並“刪除”第一個字段(或者更確切地說將其設置為null; $1="" )。 最后的1啟用默認打印。 HTH。

你不能這樣做,但還有另一種方法:

sed ':a;s/^\([0-9]*\):\([^:]*\):/\1:\2\1/;ta;s/://' input

說明

do {                                                           // a:
  1) match numbers at the beginning and a `:`                  // ^\([0-9]*\):
  2) match and remember everything that is not `:` upto an `:` // \([^:]*\):
  3) swap the `:` with the number from 1 (keep the first `:`)  // /\1:\2\1/
} while (there are matches)                                    // ta
finally delete the `:` after the number                        // s/://

這可能適合你(GNU sed):

sed -r ':a;s/^(([^:]*):.*):|:/\1\2/;ta' file

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM