【发布时间】:2015-11-26 07:22:05
【问题描述】:
您好,需要替换文件中的字符串仅在文件的第 n 行
文件1
hi this is line 1
hi this is line 2
hi this is line 3
hi this is line 4
我只需要在第 2 行替换 'hi'
专家如下
hi this is line 1
Hello this is line 2
hi this is line 3
hi this is line 4
我尝试创建一个临时文件
sed -n 2p file1 > temp1
perl -pi -e 's/hi/Hello/g' temp1 \\I tried to replace temp1 with line 2 in file1
sed -i '2d' file1 \\after this I failed to insert temp1 as a 2nd line in file1
帮我在第N行替换文件中的一个字符串(最好没有临时文件..)。
谢谢
【问题讨论】:
-
如果你已经可以使用 perl 那么我建议:
my $i=0;while(<>){$i++; if($i==2){s/^hi/Hello/};print;}