该文件有 200 行,每行都是相同的:
first,second,third
当我跑步时
awk -F"," '{$2="new second";print $0 > FILENAME}' OFS="," test
我会得到214行。最后 16 行是
201 ,new second,third
202 first,new second,third
203 first,new second,third
204 first,new second,third
205 first,new second,third
206 first,new second,third
207 first,new second,third
208 first,new second,third
209 first,new second,third
210 first,new second,third
211 first,new second,third
212 first,new second,third
213 first,new second,third
214 fi,new second
我遇到过这种情况,这意味着结果不正确很多次。每次都会减少行号。但是这个例子增加了行号,并且有些行是错误的:
,new second,third
fi,new second
答案1
在处理它时重定向到同一文件会导致奇怪的结果。
如果您想覆盖原始文件,可以将输出重定向到新文件,然后将其移回:
awk -F"," '{$2="new second";print > FILENAME".new"}' OFS="," test && mv test.new test
或者
awk -F"," '{$2="new second";print}' OFS="," test > test.new && mv test.new test