Computing.Net > Forums > Unix > replacing a string in a file

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

replacing a string in a file

Reply to Message Icon

Name: BHubb
Date: April 9, 2004 at 22:15:14 Pacific
OS: HP 11ux
CPU/Ram: 900mhz/8gb
Comment:

If a file in unix has the string "123ABC" in it on 50 different lines and I only want to replace the first 25 of them with "xxxxxx", how would I do that with a unix command??

Thanks for any help or info you can provide...

Hubb



Sponsored Link
Ads by Google

Response Number 1
Name: aigles
Date: April 10, 2004 at 11:07:58 Pacific
Reply:

Try the following script :

#!/usr/bin/awk -f
# subn str= by= count= input_file
# str = string to be replace
# by = replacement string
# count = max replacement count
#
{
   if (count == "")
      gsub(str, by);
   else {
      while (count>0) {
         if (sub(str, by))
            count--;
         else
            break;
      }
   }
   print;
}

subn str="123ABC" by="xxxxxx" count=25 input_file

Jean-Pierre.


0

Response Number 2
Name: FishMonger
Date: April 11, 2004 at 08:35:27 Pacific
Reply:

I didn't test it, but this should work.

from the command line:
perl -pi -e 'if(s/123ABC/xxxxxx/){$i++; last if($i==25)}' input_file


0

Response Number 3
Name: FishMonger
Date: April 11, 2004 at 08:41:23 Pacific
Reply:

I think it will also work if we condense it a little more, like this:

perl -pi -e 'if(s/123ABC/xxxxxx/){last if ($i++==25)}' input_file


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: replacing a string in a file

change string in multiple file www.computing.net/answers/unix/change-string-in-multiple-file/4697.html

Replace a string in Script www.computing.net/answers/unix/replace-a-string-in-script/7047.html

Insert string in a txt file..? www.computing.net/answers/unix/insert-string-in-a-txt-file/6089.html