replace a column in a file if it matches certain pattern

Hi,

I want to replace a column in a file if it matches certain pattern. Can you help me on this.

Here is the file content.

000000 1111111 2222222
011111 0123445 1234556
023445 1111111 2343455

if second column contains 1111111 i need to replace it with 0000000

Can you help me on this.

nawk -v col=2 -v val=1111111 -v valN=0000000 '$col == val {$col = valN}1' myFile

Its erroring out.

$ cat test
000000 1111111 2222222
011111 0123445 1234556
023445 1111111 234345
$ nawk -v col=2 -v val=1111111 -v valN=0000000 '$col == val {$cal = valN}1' test
nawk: illegal field $()
 input record number 1, file test
 source line number 1
$

Okie i got it. its working now.there was a typo error $cal it should be $col. Can you explain me the command please. Because i have lot of files like this. Want to do different things.

Ooops - my bad - sorry 'bout that - fixed the post.

nawk -v col=2 -v val=1111111 -v valN=0000000 '$col == val {$col = valN}1' myFile

'-v col=2' - we're assigning awk's variable 'col' a value of '2' - this is your COLUMN designator.

'-v val=1111111' - we're assigning awk's variable 'val' a value of '1111111 ' - this is your OLD value.

'-v valN=0000000' - we're assigning awk's variable 'valN' a value of '0000000' - this is your NEW value.

# if the VALUE of the field/column referenced by var 'col' equals the value of
# variable 'val' (or OLD value), then assign the value of variable 'valN'
# to the column/field referenced by variable 'col'.
#
'$col == val {$col = valN}1' 

Thanks..That worked great..Awesome.

Here is also a KornShell version, which is longer than the proposed solution,
however it works with an arbitrary number of columns and you don't need to specify yourself the number of column:

#!/bin/ksh

IFS=" \t\n"

current_result=""
final_result=""

while read current_line
do
    
    current_result=""
    
    for current_token in $current_line
    do
        if [[ $current_token = "1111111"  ]]
        then
            current_result="$current_result 0000000"
        else
            current_result="$current_result $current_token"
        fi
    done
    
    current_result="${current_result# }"
    
    final_result="$final_result$current_result\n"
    
done < $1

final_result="${final_result%\\n}"

exec 4> $1
print -u4 "$final_result"

1 <&-
4 >&-

Where $1 is the name of your file in which you want to replace "11111111".

Regards,
:slight_smile: