使用条件重命名带有 awk 的列的值

Using conditional to rename the values of a column with awk

我使用的数据集在数据集的第二列有一个名为“Store”的字段。

"Store"
  A
  B
  C
  A

以下代码无效。我想要的是将“A”值重命名为“A_store”

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

期望的输出:

"Store"
A_store
B_store
C_store
A_store

我不清楚你的目标,但也许这会有所帮助:

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) ="_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 && =="A") ="_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 &&  == "A") ="_store"; else if(NR>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

此外,如果您的字符串中有空格,您将需要稍微更改您的代码,例如

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 &&  ~ "A") ="_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

这是否解决了您的问题?

如果 OP 想要保留逗号(正如“output.csv”所暗示的那样),那么

样本输入

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

代码

{m,g}awk 'BEGIN{ _+=_^=FS=OFS="," } sub("^A$","&_store",$_)^!_' 

   or

{m,g}awk 'sub("^A$","&_store",$(!_+!_))^_' FS=, OFS=,

   or

{m,g}awk 'sub("^A$","&_store",)^_' FS=',' OFS=','

样本输出

"misc","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
# data.csv
foo,"Store",bar
1,AA,1
2,B,1
3,C,1
4,A,1 
 
$ awk -F, -vOFS=, 'NR>1&&=="A"{="_store"}1' data.csv
foo,"Store",bar
1,AA,1
2,B,1
3,C,1
4,A_store,1

trim 空格

# data.csv
foo,"Store",bar
1,AA,1
2,B,1
3,  A  ,1
4,A,1

$ awk -F, -vOFS=, 'NR>1 &&  ~ /^[ ]*A[ ]*$/ {gsub(/^[ \t]+/, "", ); gsub(/[ \t]+$/, "", ); ="_store"}1' data.csv
foo,"Store",bar
1,AA,1
2,B,1
3,A_store,1
4,A_store,1