Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Original file

123|abc|heloo good morning friends|1|123|abc|123|abc
123|abc|heloo good morning everyone|1|123|abc|123|abc

Replaced file

123|abc|heloo good morning freinds|1|123|abc|123|abc
123|abc|this is what i want to see|1|123|abc|123|abc

Here as you can see the separator is |. Now if any block contains the word "everyone" that particular block should be changed to "this is what i want to see".

share|improve this question

2 Answers 2

Just loop through the fields and check if they match or not:

awk 'BEGIN{FS=OFS="|"}
     {for (i=1; i<=NF; i++)
           if ($i ~ "everyone") $i="this is what i want to see"
      print}' file

See output:

$ awk 'BEGIN{FS=OFS="|"} {for (i=1; i<=NF; i++) if ($i ~ "everyone") $i="this is what i want to see"; print}' file
123|abc|heloo good morning friends|1|123|abc|123|abc
123|abc|this is what i want to see|1|123|abc|123|abc

In a more idiomatic way, the if condition can be written as ($i ~ "everyone") && $i="this is what i want to see" and then just use a true condition to print the lines:

awk 'BEGIN{FS=OFS="|"} {for (i=1; i<=NF; i++) ($i ~ "everyone") && $i="this is what i want to see"} 1' file
share|improve this answer
sed 's/[^|]*everyone[^|]*/this is what I want to see/g' <<\DATA
123|abc|heloo good morning friends|1|123|abc|123|abc                       
123|abc|heloo good morning everyone|1|123|abc|123|abc
DATA

OUTPUT

123|abc|heloo good morning friends|1|123|abc|123|abc
123|abc|this is what I want to see|1|123|abc|123|abc

This matches any occurence of everyone and the entire sequence to either left or right of it up to but not including the separator |. So the above works. But so does:

sed 's/[^|]*everyone[^|]*/replace/g' <<\DATA
everyone|everyevery|every|one|                                             
everyone|everyone|heloo good morning everyone|everyone|123|abc|123|abc
DATA

OUTPUT

replace|everyevery|every|one|
replace|replace|replace|replace|123|abc|123|abc
share|improve this answer
    
this will not work. OP needs to apply only for strigns with everyone. And obviously not only for the second line. –  rush Jul 30 at 10:24
1  
Look more carefully on patterns to replace. ps. downvote is not from me. –  rush Jul 30 at 10:28
    
@rush - dang man. How'd I miss that? I deserved the downvote - it all blended in. Anyway, that's fixed. –  mikeserv Jul 30 at 10:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.