简体   繁体   English

使用SED修改文件的第n行

[英]Using SED to modify the nth line of a file

If I want to add content to the 10th line of a file, how do I do it? 如果要在文件的第10行添加内容,该怎么做?

This is what I came up with: 这是我想出的:

sed -ie '' "10s/^/new_content/g" file.txt

I keep getting the message "no such file or directory" 我不断收到消息“没有这样的文件或目录”

Also, if I want to replace 10 with N+1 and the new_content with a variable $VAR, would the format still be the same? 另外,如果我想用N + 1替换10并用变量$ VAR替换new_content,格式是否仍将相同?

VAR= $(cat fileA.txt)
sed -ie '' "`expr $N +1`s/^/$VAR/g" fileB.txt

Thanks for your help!!! 谢谢你的帮助!!!

Shell is fussy about spacing: 壳牌对间距很挑剔:

VAR= $(cat fileA.txt)

You do not want the space after the = . 您不需要=后的空格。 Actually, you don't want the assignment either, unless fileA.txt has only one line. 实际上,除非fileA.txt只有一行,否则您也不需要分配。 You'd have to escape newlines with backslashes, etc, to get it to work, which is both hard and unnecessary. 为了使它能够正常工作,您必须使用反斜杠等使转义符转义,这既困难又不必要。

Unless you're using an antique (non-POSIX) shell, use built-in arithmetic: 除非您使用的是古董(非POSIX)外壳,否则请使用内置算法:

sed -i.bak -e "$(($N + 1))r fileA.txt" fileB.txt

The $(($N + 1)) has the shell evaluate the arithmetic expression. $(($N + 1))使shell评估算术表达式。 The r has sed read the file that is named. rsed读取了命名的文件。

[1addr]r file
Copy the contents of file to the standard output immediately before the next attempt to read a line of input. 在下一次尝试读取输入行之前,立即将文件内容复制到标准输出。 If file cannot be read for any reason, it is silently ignored and no error condition is set. 如果由于某种原因无法读取文件,它将被静默忽略,并且不会设置任何错误条件。

It turns out I needed to split -i and -e . 事实证明,我需要拆分-i-e

The final result that works was: 起作用的最终结果是:

        sed -i '' -e "10s/^/CONTENT/g" file.txt

Or to increase Ns by +1 each time it loops: 或者在每次循环时将ns增加+1:

        sed -i '' -e "$((N + 1))s/^/CONTENT/g" ~/dance/heatlist/prep.txt

I still have not figured out how to make CONTENT a variable $CONTENT 我仍然没有弄清楚如何使CONTENT成为变量$ CONTENT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM