【问题标题】:Replacing a string in nth line a file替换文件第 n 行中的字符串
【发布时间】: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;}

标签: bash unix replace sed


【解决方案1】:

以上答案是正确的,但我很想将 AWK 变体仅供参考。

awk 'NR==2{gsub("hi","Hello",$1)}; {print $0}' file > newfile

【讨论】:

    【解决方案2】:

    这可能对你有用:

    sed -i '2s/hi/Hello/' file
    

    【讨论】:

      猜你喜欢
      • 2015-07-07
      • 2019-03-17
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      相关资源
      最近更新 更多