vi, awk, sed - Substitute / Replace Few First , Last Characters in all lines of Linux file

advertisements

_____________________________________________________________________________________________________________________

The Eucharistic Miracles of the World

I have a text file called dat.txt and it having some text data which is highly confidential. I wanted to replace some few characters with x to make it invalid. See different options with vi, awk, sed.


My input file is-
$ cat dat.txt
1-CCJGL1-CCJGL1-CCJGL
1-BSDF0Q1-BW;LKJ1-BWP30Q
1-LKJ<MN1-1LKJMG1-1W13LG
1-2<MBMV1-NVNBVKJH21HMRE
1-2EW*&Y1-(878761-2AJKGY
Using vi editor:
Open the file in vi and run following commands.
  1. To replace last 6 characters with x
:%s/......$/xxxxxx/g

  1. To replace first 6 characters with x
:%s/^....../xxxxxx/g

Using awk:

awk '{
    start_str=substr($0,1,6)
    gsub(/./,"x",start_str)
    finish_str=substr($0,6)
    print start_str finish_str
}' dat.txt

Output
xxxxxxGL1-CCJGL1-CCJGL
xxxxxxF0Q1-BW;LKJ1-BWP30Q
xxxxxx<MN1-1LKJMG1-1W13LG
xxxxxxBMV1-NVNBVKJH21HMRE
xxxxxx*&Y1-(878761-2AJKGY


awk '{
    len=length($0)
    start_str=substr($0,len-5,len)
    finish_str=substr($0,1,len-6)
    gsub(/./,"x",start_str)
    print finish_str start_str
}' dat.txt

Output
1-CCJGL1-CCJGL1xxxxxx
1-BSDF0Q1-BW;LKJ1-xxxxxx
1-LKJ<MN1-1LKJMG1-xxxxxx
1-2<MBMV1-NVNBVKJHxxxxxx
1-2EW*&Y1-(878761-xxxxxx

Using sed:

sed -r "s/^(.{0})(.{6})/\1xxxxxx/" dat.txt
Output
xxxxxxL1-CCJGL1-CCJGL
xxxxxx0Q1-BW;LKJ1-BWP30Q
xxxxxxMN1-1LKJMG1-1W13LG
xxxxxxMV1-NVNBVKJH21HMRE
xxxxxx&Y1-(878761-2AJKGY

sed -r "s/(.{0})(.{6})$/\1xxxxxx/" dat.txt
Output
1-CCJGL1-CCJGL1xxxxxx
1-BSDF0Q1-BW;LKJ1-xxxxxx
1-LKJ<MN1-1LKJMG1-xxxxxx
1-2<MBMV1-NVNBVKJHxxxxxx
      1-2EW*&Y1-(878761-xxxxxx

_____________________________________________________________________________________________________________________

Website Stats

0 comments:

Post a Comment

Labels

Oracle (629) Script (86) General (77) Unix (47) Blog (23) Technology (19) gadget (6) games (6) Business (3) OCI (3) SQL* Loader (3) Datapump (2)
 

acehints.com Copyright 2011-23 All Rights Reserved | Site Map | Contact | Disclaimer