awk and gsub - how to replace only the first X occurrences


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting awk and gsub - how to replace only the first X occurrences
# 1  
Old 09-24-2010
awk and gsub - how to replace only the first X occurrences

I have a text (text.txt) and I would like to replace only the first 2 occurrences of a word (but I might need to replace more):

For example, if text is this:

Code:
CAR sweet head
hat red yellow
CAR book brown
tiger CAR cow CAR
CAR milk

I would like to replace the word "CAR" with word "REPLACE" only in row 1 and 3 but not in row 4 and 5 and I would like to obtain a result like this:

Code:
REPLACE sweet head
hat red yellow
REPLACE book brown
tiger CAR cow CAR
CAR milk

but if I use:

Code:
cat text.txt | awk '{gsub("CAR","REPLACE");print}'

I will obtain this:

Code:
REPLACE sweet head
hat red yellow
REPLACE book brown
tiger REPLACE cow REPLACE
REPLACE milk

Is there a way to obtain what i need (if possible using awk and gsub)?

Thanks in advance.
# 2  
Old 09-24-2010
Code:
$ ruby -00 -ne 'print $_.split("CAR",3).join("REPLACE")' file
REPLACE sweet head
hat red yellow
REPLACE book brown
tiger CAR cow CAR
CAR milk

# 3  
Old 09-24-2010
Code:
cat text.txt |
awk '/CAR/{
  if ( count < 2 ){ gsub("CAR","REPLACE")}
  count++
  print
  }'

...oh... and you can pass in the 2 as a variable:

Code:
cat text.txt |
awk '/CAR/{
  if ( count < counter ){ gsub("CAR","REPLACE")}
  count++
  print
  }' counter=$counter

# 4  
Old 09-24-2010
Thanks, but using awk and gsub?

I don't know ruby and I would like to use awk because so I could adapt the script to my needs.

Thanks again

---------- Post updated at 04:44 PM ---------- Previous update was at 04:43 PM ----------

Thanks again, I had not seen the last message

---------- Post updated at 04:55 PM ---------- Previous update was at 04:44 PM ----------

@quirkasaurus

I have tested your first code but I obtain this output:

Code:
REPLACE sweet head
REPLACE book brown
tiger CAR cow CAR
CAR milk

The second row is deleted

---------- Post updated at 04:59 PM ---------- Previous update was at 04:55 PM ----------

With this code it runs:

Code:
cat text.txt | awk '{if ( count < 3 ){ gsub("CAR","REPLACE")} count++; print}'

# 5  
Old 09-24-2010
oops. sorry. didn't notice that.

Code:
cat text.txt |
awk '{
  if ( count < 2 ){
    gsub("CAR","REPLACE")
    count++
    }
  print
  }'

Code:
output:
REPLACE sweet head
hat red yellow
CAR book brown
tiger CAR cow CAR
CAR milk

# 6  
Old 09-24-2010
I need a code like this because, since I have a big file where to search, I would like to stop search at first 2 occurrences found but with gsub I think search is done until the end of file, instead with this code (using sub in place of gsub):

Code:
cat text.txt | awk '{sub("CAR","REPLACE");print}'

search is done until awk find the occurence. Is it right?
# 7  
Old 09-24-2010
quirkasaurus,
your code is not replacing 2nd occurance.

slightly change in your code
Code:
awk '/CAR/ && count < 2  {gsub("CAR","REPLACE");count++} {print $0}' infile

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

awk gsub command to replace multiple spaces

Hi Forum. I'm trying to cleanup the following data elements (To remove any occurences of commas and any extra spaces) while preserving the <TAB> delimiter using awk gsub but I have not been successful. Original Data: 4365 monte des source rue,, ,<TAB>trevost<TAB>QC Desired Data:... (1 Reply)
Discussion started by: pchang
1 Replies

2. Shell Programming and Scripting

Replace characters in string with awk gsub

Hi I have a source file that looks like a,b,c,d,e,f,g,h,t,DISTI(USD),MSRP(USD),DIST(EUR),MSRP(EUR),EMEA-DISTI(USD),EMEA-MSRP(USD),GLOBAl-DISTI(USD),GLOBAL-MSRP(USD),DISTI(GBP), MSRP(GBP) I want to basically change MSRP(USD) to MSRP,USD and DIST(EUR) to DIST,EUR and likewise for all i'm using... (3 Replies)
Discussion started by: r_t_1601
3 Replies

3. Shell Programming and Scripting

Search & Replace content of files using gsub in awk

Hi,I have 2 files master.txt & reference.txt as shown below & i require o/p as mentioned in file 3 using awk but content is not replacing properlymaster.txt:... (15 Replies)
Discussion started by: siramitsharma
15 Replies

4. Shell Programming and Scripting

Search & replace content using awk/gsub

Hi, I have two files master.txt & reference.txt. Sample below Master.txt 2372,MTS,AP 919848001104,Airtel,DL 0819,MTS,MUM 919849788001,Airtel,AP 1430,Aircel MP,20 Reference.txt 2372,919848701430,46467 919848002372,2372,47195 2372,919849788001,59027 0819,028803,1 0819,029801,1... (2 Replies)
Discussion started by: siramitsharma
2 Replies

5. Shell Programming and Scripting

awk + gsub to search multiple input values & replace with located string + extra text

Hi all. I have the following command that is successfully searching for any one of the strings on all lines of a file and replacing it with the instructed value. cat inputFile | awk '{gsub(/aaa|bbb|ccc|ddd/,"1234")}1' > outputFile This does in fact replace any occurrence of aaa, bbb,... (2 Replies)
Discussion started by: dazhoop
2 Replies

6. Shell Programming and Scripting

Using of gsub function in AWK to replace space by underscore

I must design a UNIX script to monitor files whose size is over a threshold of 5 MB in a specific UNIX directory I meet a problem during the for loop in my script. Some file names contain spaces. ls -lrt | awk '$5>=5000000 && length($8)==5 {gsub(/ /,"_",$9); print};' -rw-r--r-- 1 was61 ... (2 Replies)
Discussion started by: Scofield38
2 Replies

7. UNIX for Dummies Questions & Answers

Replace all occurrences of strings with parentheses

Hi, I tried to adapt bartus's solution to my problem, without success. I want to replace all the occurences of this: with: , where something can contain an arbitrary number of balanced parens and brakets. Any ideas ? Best, (1 Reply)
Discussion started by: ff1969ff1969
1 Replies

8. Shell Programming and Scripting

sed replace multiple occurrences on the same line, but not all

Hi there! I am really enjoying working with sed. I am trying to come up with a sed command to replace some occurrences (not all) in the same line, for instance: I have a command which the output will be: 200.300.400.5 0A 0B 0C 01 02 03 being that the last 6 strings are actually one... (7 Replies)
Discussion started by: ppucci
7 Replies

9. Shell Programming and Scripting

awk gsub

Hi all I want to do a simple substitution in awk but I am getting unexpected output. My function accepts a time and then prints out a validation message if the time is valid. However some times may include a : and i want to strip this out if it exists before i get to the validation. I have shown... (4 Replies)
Discussion started by: pxy2d1
4 Replies

10. Shell Programming and Scripting

Help with AWK and gsub

Hello, I have a variable that displays the following results from a JVM.... 1602100K->1578435K I would like to collect the value of 1578435 which is the value after a garbage collection. I've tried the following command but it looks like I can't get the > to work. Any suggestions as... (4 Replies)
Discussion started by: npolite
4 Replies
Login or Register to Ask a Question