问题描述
我有一种情况,我想要一个 bash 脚本来替换文件中的整行.行号始终相同,因此可以是一个硬编码变量.
I have a situation where I want a bash script to replace an entire line in a file.The line number is always the same, so that can be a hard-coded variable.
我不想替换该行中的某些子字符串,我只想用新行完全替换该行.
I'm not trying to replace some sub-string in that line, I just want to replace that line entirely with a new line.
是否有任何 bash 方法可以执行此操作(或一些可以放入 .sh 脚本的简单方法).
Are there any bash methods for doing this (or something simple that can be thrown into a .sh script).
推荐答案
不是最好的,但应该可以:
Not the greatest, but this should work:
sed -i 'Ns/.*/replacement-line/' file.txt
其中 N
应替换为您的目标行号.这将替换原始文件中的行.要将更改的文本保存在不同的文件中,请删除 -i
选项:
where N
should be replaced by your target line number. This replaces the line in the original file. To save the changed text in a different file, drop the -i
option:
sed 'Ns/.*/replacement-line/' file.txt > new_file.txt
这篇关于如何按行号替换文本文件中的整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!