使用awk和sed将一些值插入到文件中

时间:2021-01-05 16:52:22

Let's imagine there is some file.txt with such data:

让我们假设有一些带有这些数据的file.txt:

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

Then I have to insert missed values, here they are:

然后我必须插入错过的值,这里是:

expected=3434,observed=0000

in proper fields before "fail". Also I have $line_number where it should be inserted:

在“失败”之前的适当领域。我还有$ line_number应该插入它:

 @@comp34,error,3434,0000,fail

I tried different solutions but they don't work. e.g.:

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

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

1 个解决方案

#1


2  

You can try this awk:

你可以尝试这个awk:

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

Output will be:

输出将是:

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

#1


2  

You can try this awk:

你可以尝试这个awk:

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

Output will be:

输出将是:

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