bash - 替换文件第 n 行中的字符串

标签 bash unix replace sed

您好需要替换文件中的字符串仅在文件的第 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 行文件中的一个字符串(最好没有临时文件..)。

谢谢

最佳答案

这可能对你有用:

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

关于bash - 替换文件第 n 行中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32325121/

相关文章:

string - 替换字符串 vb6 中除数字以外的所有内容

json - 遍历数组 : Cannot index array with string "<key>" 时出现 jq 错误

bash - 使用 awk 或 bash 将字符串附加到列中单元格的所有元素

bash - 在字段中查找重复项并在 unix bash 中打印它们

python - 如何在 Python 中使用 psutil 获取程序的最大内存使用量

Groovy 中的 Unix FIND 命令

python - pandas 仅替换列的一部分

javascript - 如何在 Android 中为 WebView 中的 Javascript 转义 MathML 字符串

linux - Bash:无法在 Linux 上启动使用 make 创建的程序

linux - 识别单个 unix 目录中文本文件中的模式