简体   繁体   中英

replacing column field separator using sed

I have a text file 1.txt:

cam:45c62741b9c99e1dcf3c140e8e3df635::dv:johnybold@yahoo.com:83.228.32.24
gamer:3dabd5bd7984b0286eba52d4a7db2dea:$Wm?1Z3MPErXl7%yk^Pc#%iu\9LFc{:octopus@vida.tv:93.182.154.63
:adc0a54f8d21694848200ae043fa99f2:GqJ:LOLPELIC@trash-mail.com:84.176.127.30
! Aa:da99417e29ab0aa67f97db64f091836b:k_P:prus_da@yahoo.com:82.179.236.154

I want to change the column separator (currently it is ':') to '||o||'. I want to change only the 1st, 3rd and 4th column separator as 2nd column contains something like hash:salt .

The script I am trying is:

sed 's/:/||o||/1;s/:/||o||/2;s/:/||o||/2' 1.txt

The only problem is in the results where ':' is included in the salt. The output I am getting is:

cam||o||45c62741b9c99e1dcf3c140e8e3df635:||o||dv||o||johnybold@yahoo.com:83.228.32.24
gamer||o||3dabd5bd7984b0286eba52d4a7db2dea:$Wm?1Z3MPErXl7%yk^Pc#%iu\9LFc{||o||octopus@vida.tv||o||93.182.154.63
||o||adc0a54f8d21694848200ae043fa99f2:GqJ||o||LOLPELIC@trash-mail.com||o||84.176.127.30
! Aa||o||da99417e29ab0aa67f97db64f091836b:k_P||o||prus_da@yahoo.com||o||82.179.236.154

The first line of the output is wrong.

Expected output :
cam||o||45c62741b9c99e1dcf3c140e8e3df635::dv||o||johnybold@yahoo.com||o||83.228.32.24

Rest of the output is correct.

What I am expecting is replace first ':' from forward and second and third time the replacement should be from backwards, so that ':' in the salt gets ignored.

Try this:

(?:^[^:]*\K:)|(:(?=[^:]+:?[^:]+$))

Basic idea:

  • Either get the first : that occurs in the line
  • Or : that is followed by at most one other :

Demo: regex101

Demo with substitution: regex101

How to run it with perl :

perl -p -e 's/(?:^[^:]*\K:)|(:(?=[^:]+:?[^:]+$))/||o||/g' input.txt

Short sed solution:

sed -E 's/:+/||o||/3g; s/:/||o||/' file

The output:

cam||o||45c62741b9c99e1dcf3c140e8e3df635::dv||o||johnybold@yahoo.com||o||83.228.32.24
gamer||o||3dabd5bd7984b0286eba52d4a7db2dea:$Wm?1Z3MPErXl7%yk^Pc#%iu\9LFc{||o||octopus@vida.tv||o||93.182.154.63
||o||adc0a54f8d21694848200ae043fa99f2:GqJ||o||LOLPELIC@trash-mail.com||o||84.176.127.30
! Aa||o||da99417e29ab0aa67f97db64f091836b:k_P||o||prus_da@yahoo.com||o||82.179.236.154

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM