2016-11-11 39 views
2

我現在有這個原始的字符串:AWK bash的重複模式

mklink .\Oracle\MOLT_HYB_01\110_Header\pkg_cdc_util.pks $.\Oracle\MOLT_HYB_01\110_Header\pkg_cdc_util.pks 
#.......................................................^ 

....並需要更換如下:

mklink .\Oracle\MOLT_HYB_01\110_Header\pkg_cdc_util.pks ..\..\..\..\.\Oracle\MOLT_HYB_01\110_Header\pkg_cdc_util.pks 
#.......^......^...........^..........^.................^^^^^^^^^^^^ 

如更換$與 「.. \」基於ORIGINAL字符串第二列(「。\ Oracle \ MOLT_HYB_01 \ 110_Header \ pkg_cdc_util.pks」)中斜槓數量的4倍。

我可以例如單獨執行以下操作:

  1. awk -F '\\' '{print NF-1}' - >打印反斜槓出現的
  2. sed -e "s,\\\,$(printf '..\\\%.0s' {1..4}),g"號 - >更換和重複字符串模式

......但不確定如何在1個命令行中串起來。

+0

[編輯]您的問題和使用編輯器'{}'按鈕固定代碼和樣本的格式化輸入輸出。還要說明你的輸入字符串是在文件中還是在shell變量中,還是在管道中或別的什麼地方。 –

回答

2

一個awk命令可以使用任意數量的輸入行(wit小時相同的字段結構):

awk -v prefixUnit="..\\" '{ 
    count = gsub("\\\\", "\\", $2) # count the number of "\"s 
    # Build the prefix composed of count prefixUnit instances 
    prefix = ""; for (i=1; i<=count; ++i) prefix = prefix prefixUnit 
    $3 = prefix substr($3, 2) # prepend the prefix to the 3rd field, replacing the "$" 
    print # print result 
}' file 

作爲稠一行程序:

awk -v pu="..\\" '{n=gsub("\\\\","\\",$2);p="";for(i=1;i<=n;++i)p=p pu;$3=p substr($3,2);print}' file 
+1

所有有用的答案,但因爲我有多條線,這工作。謝謝你們。 –

0

我用perl,雖然這是一個位 「聰明」

perl -ane ' 
    $n = ($F[1] =~ tr/\\/\\/); 
    $F[2] =~ s{\$}{"..\\" x $n}e; 
    print join(" ", @F); 
' file 

其中

  • -a - 自動分割行成陣列@F
  • -n - 執行機構「文件」的每一行
  • $F[1] =~ tr/\\/\\/ - 計數第二個字段中反斜槓的數量
  • $F[2] =~ s{\$}{"..\\" x $n}e - 用正確的號碼的 「.. \」
0

AWK一個班輪取代美元,假設有隻是一個單一的線,年加工

awk -F\\ -v RS='$' -v ORS='' '{print} NR==1{for(i=1; i< NF; i++) printf("..\\")}' 

說明

awk -F\\ -v RS='$' ' -v ORS='' ' # Specify separators 

    {print}      # print the line 

    NR==1{      # for first record 
     for (i=1; i<NF; i++)  # print multiple ..\ 
     printf("..\\")   # need to escape \\ 
    } 
'