awk +更改列值并保留双引号

时间:2015-01-11 22:52:20

标签: awk

我有这些数据:

$ head test
"Rec Open Date","MSISDN","IMEI"
"2015-01-04",100,200
"2015-01-04",100,200
"2015-01-04",100,200
"2015-01-04",100,200
"2015-01-04",100,200
"2015-01-04",100,200
"2015-01-04",100,200
"2015-01-04",100,200
"2015-01-04",100,200

我可以使用此命令更改第一列的值:

$ awk -F, 'NR>1{$1="2015-01-05"}1' OFS=, test > tmpfile && mv tmpfile test

用这个命令我松开双引号,我想保留双引号。可以修改此命令以实现此目的吗?

$ head test
"Rec Open Date","MSISDN","IMEI"
2015-01-05,100,200
2015-01-05,100,200
2015-01-05,100,200
2015-01-05,100,200
2015-01-05,100,200
2015-01-05,100,200
2015-01-05,100,200
2015-01-05,100,200
2015-01-05,100,200

2 个答案:

答案 0 :(得分:1)

来自GNU Awk用户指南的

;

  

\"文字双引号(仅限字符串常量)。这个   当你想写一个字符串常量时,使用sequence   包含双引号。因为字符串是由double分隔的   引号,你需要转义作为字符串一部分的引用   为了告诉awk继续处理字符串的其余部分。

$ awk -F, 'NR>1{$1="\"2015-01-05\""}1' OFS=, test > tmpfile && mv tmpfile test

$ head test
"Rec Open Date","MSISDN","IMEI"
"2015-01-05",100,200
"2015-01-05",100,200
"2015-01-05",100,200
"2015-01-05",100,200
"2015-01-05",100,200
"2015-01-05",100,200
"2015-01-05",100,200
"2015-01-05",100,200
"2015-01-05",100,200

答案 1 :(得分:1)

并非您“失去”它们,而是$1最初为"something"并且您将其替换为another thing。由于此another thing是一个字符串,因此您可以使用双引号来记录它。因此,为了获得双引号,您需要在进行替换时指明。

这可以更清洁:

awk -v new='"2015-01-05"' 'BEGIN {FS=OFS=","} NR>1{$1=new}1' file
    ^^^^^^^^^^^^^^^^^^^^^                              ^
         |---------------------------------------------|
    we provide the var ............... and we replace with it
      surrounded by "