Reputation: 13
How to replace random text between :50K
and :53B
in each line with CREDIT
using shell?
The input is
{:32tyfddf:65 trfdfd :67 ghfdfd :50K:xxxxhh:53B:fg :43:fg $
{:32tyfddf:65 trfdfd :67 ghfdfd :50K:yyyyhh:53B:fg :43:fg $
{:32tyfddf:65 trfdfd :67 ghfdfd :50K:zzzzz:53B:fg :43:fg $
Upvotes: 1
Views: 4596
Reputation: 41460
Using awk
awk -F":50K|:53B" '{$2=":50KCREDIT:53B"}8' OFS="" file
{:32tyfddf:65 trfdfd :67 ghfdfd :50KCREDIT:53B:fg :43:fg $
{:32tyfddf:65 trfdfd :67 ghfdfd :50KCREDIT:53B:fg :43:fg $
{:32tyfddf:65 trfdfd :67 ghfdfd :50KCREDIT:53B:fg :43:fg $
awk '{sub(/:50K.*:53B/,":50KCREDIT:53B")}8' file
{:32tyfddf:65 trfdfd :67 ghfdfd :50KCREDIT:53B:fg :43:fg $
{:32tyfddf:65 trfdfd :67 ghfdfd :50KCREDIT:53B:fg :43:fg $
{:32tyfddf:65 trfdfd :67 ghfdfd :50KCREDIT:53B:fg :43:fg $
gnuawk
awk '{print gensub(/(:50K).*(:53B)/,"\\1CREDIT\\2","g")}' file
{:32tyfddf:65 trfdfd :67 ghfdfd :50KCREDIT:53B:fg :43:fg $
{:32tyfddf:65 trfdfd :67 ghfdfd :50KCREDIT:53B:fg :43:fg $
{:32tyfddf:65 trfdfd :67 ghfdfd :50KCREDIT:53B:fg :43:fg $
Upvotes: 2
Reputation: 6423
Using Perl:
perl -pi.bak -e 's/(\:50K).+?(\:53B)/${1}CREDIT${2}/g;' input_file
Basic usage:
s/replace_this/with_this/g;
(\:50K)
and (\:53B)
in replace this
part are in parenthesis because these are so called capturing groups. You can refer to these capturing groups as ${1}
and ${2}
(or \1
and \2
) in the with_this
part, CREDIT
as literal replacing whatever is in between ( .+?(\:53B)
- means whatever character, whatever number of occurrences until :53B appears).
:
is escaped because it's a metacharacter in regex.
Backup of the file will be saved to input_file.bak
Using your input, the output is:
$ cat input_file
{:32tyfddf:65 trfdfd :67 ghfdfd :50KCREDIT:53B:fg :43:fg $
{:32tyfddf:65 trfdfd :67 ghfdfd :50KCREDIT:53B:fg :43:fg $
{:32tyfddf:65 trfdfd :67 ghfdfd :50KCREDIT:53B:fg :43:fg $
Hope it helps.
Upvotes: 1
Reputation: 60067
sed 's/:50K.*:53B/:50KCREDIT:53B/g'
A basic sed replace expression:
s/what_to_look_for/what_to_replace_with/
g
means "do it for all found patterns on the line" (you might want to skip that).
Usage: You use sed by either letting it read from stdin:
cat path/to/your_text_file | sed 's/:50K.*:53B/:50KCREDIT:53B/g'
or by suplying the text file in which you want to replace as an argument
sed 's/:50K.*:53B/:50KCREDIT:53B/g' path/to/your_text_file
Each will print the replace version to stdout. Neither will modify the original file in place.
Upvotes: 1