Home > Mobile >  How to replace words in file in bash
How to replace words in file in bash

Time:12-16

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?

CodePudding user response:

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.

CodePudding user response:

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
  • Related