简体   繁体   中英

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?

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?

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. 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:

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

The $(($N + 1)) has the shell evaluate the arithmetic expression. The r has sed read the file that is named.

[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 .

The final result that works was:

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

Or to increase Ns by +1 each time it loops:

        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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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