Thursday, June 2, 2022

[SOLVED] Using conditional to rename the values of a column with awk

Issue

I am using a dataset with a field called "Store" at the second column of the dataset.

"Store"
  A
  B
  C
  A

The following code is not working. What I want is to rename "A" values to "A_store"

awk -F, 'BEGIN {FS=","} {if (NR!=1 && $2=="A") $2="A_store"}' output.csv

The desired output:

"Store"
A_store
B_store
C_store
A_store

Solution

Your goal isn't clear to me, but perhaps this will help:

cat test.txt
"Store", "something else", "another thing", "last thing"
A, 1, 5, q
B, 2, 6, r
C, 3, 7, s
A, 4, 8, t

awk -F"," '{if(NR>1) $1=$1"_store"; print}' test.txt
"Store", "something else", "another thing", "last thing"
A_store  1  5  q
B_store  2  6  r
C_store  3  7  s
A_store  4  8  t

awk -F"," '{if(NR>1 && $1=="A") $2=$1"_store"; print}' test.txt
"Store", "something else", "another thing", "last thing"
A A_store  5  q
B, 2, 6, r
C, 3, 7, s
A A_store  8  t

awk -F"," '{if(NR>1 && $1 == "A") $2=$1"_store"; else if(NR>1) $2=$1; print}' test.txt
"Store", "something else", "another thing", "last thing"
A A_store  5  q
B B  6  r
C C  7  s
A A_store  8  t

Also, if you have whitespace in your strings you will need to alter your code slightly, e.g.

cat test.txt
"Store", "something else", "another thing", "last thing"
  A, 1, 5, q
  B, 2, 6, r
  C, 3, 7, s
  A, 4, 8, t

awk -F"," '{if(NR>1 && $1 ~ "A") $1=$1"_store"; print}' test.txt
"Store", "something else", "another thing", "last thing"
  A_store  1  5  q
  B, 2, 6, r
  C, 3, 7, s
  A_store  4  8  t

Does that solve your problem?



Answered By - jared_mamrot
Answer Checked By - David Goodson (WPSolving Volunteer)