2017-09-11 44 views
1

我想掩飾此分隔文件中的第6列。目前我的嘗試掩蓋了整個文件。我想知道我可能做錯了什麼。Masking delimited columns shellscript

電流:

awk 'BEGIN{FS=OFS="^^"} {gsub(/./, "X", $1)} 6' $1 

輸入:

00000000001^^00023^^111112233^^C^^ ^^Iwanttomaskthis     ^^ ^^    ^^U^^W^^ ^^ ^^222^^6^^77 
00000000001^^00024^^111112233^^B^^ ^^Iwanttomaskthis     ^^ ^^    ^^X^^W^^ ^^ ^^333^^9^^88 

預計:

00000000001^^00023^^111112233^^C^^ ^^XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX^^ ^^    ^^U^^W^^ ^^ ^^222^^6^^77 
00000000001^^00024^^111112233^^B^^ ^^XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX^^ ^^    ^^U^^W^^ ^^ ^^222^^6^^77 

回答

2

您可以使用此awk

awk 'BEGIN{FS="\\^\\^"; OFS="^^"} {gsub(/./, "X", $6)} 1' file 

00000000001^^00023^^111112233^^C^^ ^^XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX^^ ^^    ^^U^^W^^ ^^ ^^222^^6^^77 
00000000001^^00024^^111112233^^B^^ ^^XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX^^ ^^    ^^X^^W^^ ^^ ^^333^^9^^88 

這裏我們需要轉義^,因爲^是一個特殊的正則表達式元字符。

+1

謝謝我也這麼想,但語法錯了。謝謝一堆! – Defcon

0

您能不能請嘗試一種方法,讓我知道這是否對您有幫助。

awk '{match($0,/\^\^ +\^\^ /);while((RLENGTH)>1){val=val?val "X":"X";RLENGTH--};sub(/\^\^ +\^\^ /,val,$0);print;val=""}' Input_file 

說明:

awk ' 
{ 
match($0,/\^\^ +\^\^ /); ##Using match functionality of awk to match regex which will look from ^^ space and ^^ space. 
while((RLENGTH)>1){  ##Now starting a while loop which will run till the value of RLENGTH is NOT NULL, not here RSTART and RLENGTH are variables which will be set once a match is found by provided regex in match function of awk. 
    val=val?val "X":"X"; ##creating a variable here and concatenating its value with stating X only each time it comes in loop. 
    RLENGTH--    ##Decrement the value of RLENGTH each time it comes in while loop. 
}; 
sub(/\^\^ +\^\^ /,"^^"val"^^ ",$0)##Substitute regex ^^ space(all spaces till) ^^ space with value of val 
print;      ##printing the current line. It could edited/non-edited depending upon regex is found by match or not. 
val=""      ##Nullifying the value of variable val here. 
} 
' file98997     ##Mentioning the Input_file here. 
0

變化甚至最後幾場。

awk '{sub(/Iwanttomaskthis     /,"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")sub(/X..W/,"U^^W")sub(/..333..9..88/,"^^222^^6^^77")}1' file 

00000000001^^00023^^111112233^^C^^ ^^XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX^^ ^^    ^^U^^W^^ ^^ ^^222^^6^^77 
00000000001^^00024^^111112233^^B^^ ^^XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX^^ ^^    ^^U^^W^^ ^^ ^^222^^6^^77