【问题标题】:insert some values into file with awk and sed使用 awk 和 sed 将一些值插入文件
【发布时间】:2016-02-16 19:39:40
【问题描述】:

假设有一些包含此类数据的 file.txt:

@@comp1,1111,1111,pass
@@comp2,2222,2222,pass
.
.
@@comp34,error,,,fail
.
.
@@comp65,6565,6565,pass

然后我必须插入遗漏的值,它们是:

expected=3434,observed=0000

在“失败”之前的正确字段中。我还有$line_number应该插入它:

 @@comp34,error,3434,0000,fail

我尝试了不同的解决方案,但它们都不起作用。 例如:

new1=`awk -n=$line_number -F, '{print $3}' text.txt` | sed 's/$new1/$expected' > text.txt
new2=`awk -n=$line_number -F, '{print $4}' text.txt` | sed 's/$new2/$observed' > text.txt

【问题讨论】:

  • 你能添加你的预期输出吗?

标签: bash awk sed


【解决方案1】:

你可以试试这个awk:

awk -F, -vln="$line" -vexpe="$expected" -vobs="$observed" 'NR==ln{$3=expe;$4=obs}1' OFS=, file

输出将是:

@@comp1,1111,1111,pass
@@comp2,2222,2222,pass
.
.
@@comp34,error,3434,0000,fail
.
.
@@comp65,6565,6565,pass

【讨论】:

  • 在插入该值后是否有可能用新的更改重写现有文件?
  • awk -i inplace '...' orig_file 使用 GNU awk 4.*。在 -vvar=... 之间不留空格已经使脚本 GNU awk 无论如何都是特定的。
猜你喜欢
  • 2015-05-06
  • 2019-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-19
  • 2018-10-20
  • 1970-01-01
相关资源
最近更新 更多