掩蔽分隔列的shellcript

时间:2017-09-11 17:54:37

标签: linux bash shell delimited-text maskedinput

我试图屏蔽此分隔文件中的第6列。目前我的尝试掩盖了整个文件。我想知道我可能做错了什么。

电流:

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

3 个答案:

答案 0 :(得分: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 :(得分: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.

答案 2 :(得分: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