vojtam
vojtam

Reputation: 1255

How to replace words in file in bash

I have a file with following content:

Blekota blaboli o koblihach.
Blanka je bl...
GEwI
er

I need to replace every word starting with Bl or bl with xxxx and save it into new file. I try this, but it did not work.

while read line; 
do pokus="${line//[Bl|bl].* /xxxx}" 
echo $pokus
done < "$TEXT" > "$TEXT".new

Desired output is:

xxxx xxxx o koblihach. 
xxxx je xxxx...
GEwI
er

What do I do wrong, please?

Upvotes: 7

Views: 5940

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133780

1st solution: Using gsub function of awk to substitute all fields which are starting from Bl OR bl then it will assign it to xxxx.

awk '{gsub(/(^[Bb]l|\<[Bb]l)[^[:space:]]+/,"xxxx")} 1' Input_file


2nd solution: With awk you could try following. Simple explanation would be traversing through each field of each line and then checking condition if it starts with Bl OR bl then assign it to xxxx and then print edited/non-edited line.

awk '{for(i=1;i<=NF;i++){if($i~/^[Bb]l/){$i="xxxx"}}} 1' Input_file

Upvotes: 3

anubhava
anubhava

Reputation: 786359

This can be done using a sed command:

sed 's/\<[Bb]l[[:alpha:]]*/xxxx/g' file

xxxx xxxx o koblihach.
xxxx je xxxx...
GEwI
er

Here \<[Bb]l[[:alpha:]]* matches a word starting with Bl or bl followed by 0 or more alphabets.

Upvotes: 8

Related Questions