如何用行号替换文本文件中的整行 [英] How to replace an entire line in a text file by line number

查看:86
本文介绍了如何用行号替换文本文件中的整行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一种情况,我希望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

这篇关于如何用行号替换文本文件中的整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆