AceVenturos
AceVenturos

Reputation: 39

Edit multiple columns in a line using awk command?

I'm trying to edit 3 columns in a file if the value in column 1 equals a specific string. This is my current attempt:

cp file file.copy
awk -F':' 'OFS=":" { if ($1 == "root1") $2="test"; print}' file.copy>file
rm file.copy

I've only been able to get the awk command working with one column being changed, I want to be able to edit $3 and $8 as well. Is this possible in the same command? Or is it only possible with separate awk commands or with a different command all together?

Edit note: The real command i'll be passing variables to the columns, i.e. $2=$var

It'll be used to edit the /etc/passwd file, sample input/output:

root:$6$fR7Vrjyp$irnF38R/htMSuk0efLSnAten/epf.5v7gfs0q.NcjKcFPeJmB/4TnnmgaAoTUE9.n4p4UyWOgFwB1guJau8AL.:17976::::::

Upvotes: 0

Views: 2069

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may use

# Fake sample values
v1=pass1
v2=pass2
awk -v var1="$v1" -v var2="$v2" 'BEGIN{FS=OFS=":"} $1 == "root1" { $2 = var1; $3 = var2}1' file > tmp && mv tmp file

See the online awk demo:

s="root1:xxxx:yyyy
root11:xxxx:yyyy
root1:zzzz:cccc"
v1=pass1
v2=pass2
awk -v var1="$v1" -v var2="$v2" 'BEGIN{FS=OFS=":"} $1 == "root1" { $2 = var1; $3 = var2}1' <<< "$s"

Output:

root1:pass1:pass2
root11:xxxx:yyyy
root1:pass1:pass2

Note:

  • -v var1="$v1" -v var2="$v2" pass the variables you need to use in the awk command
  • BEGIN{FS=OFS=":"} set the field separator
  • $1 == "root1" check if Field 1 is equal to some value
  • { $2 = var1; $3 = var2 } set Field 2 and 3 values
  • 1 calls the default print command
  • file > tmp && mv tmp file helps you "shrink" the "replace-inplace-like" code.

Upvotes: 2

Hielke Walinga
Hielke Walinga

Reputation: 2845

You can create multiple statements for the if condition with a block {}.

awk -F':' 'OFS=":" { if ($1 == "root1") {$2="test"; $3="test2";} print}' file.copy>file

You can also improve your command by using awk's default "workflow": condition{commands}. For this you need to bring the OFS to the input variables (-v flag)

awk -F':' -v OFS=":" '$1=="root1"{$2="test"; $3="test2"; print}' file.copy>file

Upvotes: 2

Related Questions