Find a line using a condition and replace a string in that line

Hello,
I have a 100 line code. I have given a sample of it below:

ABC*654654*1*54.54*21.2*87*1*654654654654
CCC*FS*FS*SFD*DSF
GGG*FGH*CGB*FBDFG*FGDG
ABC*654654*1*57.84*45.4*88*2*6546546545
CCC*WSF*SG*FGH*GHJ
ADA*AF*SFG*DFGH*FGH*FGTH

I need to select the line starting with "ABC" its 7th field should be replaced as 13
I result code should look like the one given below:

ABC*654654*1*54.54*21.2*87*13*654654654654
CCC*FS*FS*SFD*DSF
GGG*FGH*CGB*FBDFG*FGDG
ABC*654654*1*57.84*45.4*88*13*6546546545
CCC*WSF*SG*FGH*GHJ
ADA*AF*SFG*DFGH*FGH*FGTH
awk 'BEGIN {FS="*"; OFS="*"} /^ABC/ {$7="13"; print}' filename

But you're never going to learn if we just give you the answers...

That looks like a fine illustration of awk's basic principles actually :slight_smile: I'll just comment it a bit more:

# awk code blocks work like CONDITION { code } WHENTOPRINT
# For each line, { code } gets run when CONDITION is true
# and the line gets printed back out when WHENTOPRINT is true.
# The code block doesn't have to be executed for WHENTOPRINT to
# cause it to print a line.
#
# CONDITION is default true if not given.  WHENTOPRINT is default false.

awk '
# Special code section run before any lines are read
BEGIN {
        # Field separator.  It defaults to whitespace but can be anything.
        # Lines read get split on it, put into special variables $1,$2,...
        # all the way up to NF, the last field.  NF is the number, $NF is the
        # last field itself.  $0 is the entire line.
        # ( $ is an operator, by the way.  You can do N=1; print $N to print field 1)
        FS="*"
        # When the 'print' command is used, awk puts the line back
        # together from the $1,$2,...$NF fields before printing it, you can
        # control what it joins together fields with.
        OFS="*"}

# The code block gets run whenever the regex /^ABC/ is true --
# i.e. whenever the line begins with ABC.
/^ABC/ {
        # You can set fields, not just read them, handy for altering text
        # On the go.  Here, we change the 7th field into 13 for any line
        # beginning with ABC.
        $7="13";
        # You can also tell awk when to print explicitly, by using the 'print'
        # command.  By default it prints out the entire line assembled from
        # the current contents of $1,$2,...$NF
        print }' filename
1 Like

OP wanted everyline to be printed right?

awk 'BEGIN{FS="*"; OFS="*"} /^ABC/{$7="13"}1' input_file

BTW, 1 here is WHENTOPRINT which is true and prints everything by default.

--ahamed

1 Like