LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Using sed/awk to replace a string at a given position in (http://www.linuxquestions.org/questions/linux-newbie-8/using-sed-awk-to-replace-a-string-at-a-given-position-in-729368/)

anoopvraj 05-29-2009 01:21 PM

Using sed/awk to replace a string at a given position in
 
I have a sequential data file like this

1234570004400122222
1267570000800134567
...................
...................

and so on

Now I want to replace a pattern of 9 digits at the 6 th position with another patten,
say 700044001 with 700020050
I need to replace only if 700044001 occurs at 6th position, other wise no changes need be done.

How can I use 'sed' to do this ....??

pixellany 05-29-2009 01:59 PM

Homework??

Have you studied SED?

The general form you are looking for is: sed '/pattern/s/string/newstring/'

Translation: When it finds a line with "pattern", then it does one replacement on that line---replacing "string" with "newstring".

anoopvraj 05-30-2009 02:55 AM

Problem is that I dont want to change the first pattern into second pattern whenever it occurs. I want it to change it only when it occurs at the 6th column

sed -e 's/firstpattern/secondpattern/g' file
will replace all the occurences of first pattern with second pattern, I believe, and I dont want that to happen.

Since this is not a file separated by spaces as separate columns, I believe I cannot also use awk using $1, $2 etc.

colucix 05-30-2009 03:34 AM

But you can always use substr in awk.

syg00 05-30-2009 03:57 AM

Easy enuff to do in sed as well as it happens - but probably clearer in awk/perl.

pixellany 05-30-2009 07:57 AM

Quote:

Originally Posted by anoopvraj (Post 3557289)
Problem is that I dont want to change the first pattern into second pattern whenever it occurs. I want it to change it only when it occurs at the 6th column

sed -e 's/firstpattern/secondpattern/g' file
will replace all the occurences of first pattern with second pattern, I believe, and I dont want that to happen.

Since this is not a file separated by spaces as separate columns, I believe I cannot also use awk using $1, $2 etc.

Read my post more carefully...

Quote:

The general form you are looking for is: sed '/pattern/s/string/newstring/'
Use "pattern" to decide which lines to modify. When sed finds "pattern", then it does the substitution according to what follows the "s" command

pixellany 05-30-2009 07:59 AM

PS: Awk does not need spaces---you can specify the delimiter.

Really good SED and AWK tutorials here:

http://www.grymoire.com/Unix/


All times are GMT -5. The time now is 03:37 AM.