简体   繁体   中英

sed replace whole line by line number - chaining commands

I need to replace a line in a file and struggling with it. Firstly I need to find a string in the file, store this line number as a variable and then replace the whole line using the variable with a new string.

I have tried a few variations of sed and currently the code I have is as follows:

line=$(grep -n "latitude" /tmp/system.cfg |cut -f1 -d:); 
sed "{$line}s/.*/system.latitude=1.888888/" /tmp/system.cfg ;

I have run the first command and successfully set line . When echoing $line I get 176. However, the sed command does not seem to be replacing the line regardless of if I use the variable or manually place the 176 like so

sed "176s/.*/system.latitude=1.888888/" /tmp/system.cfg ;

I have also tried the following which seems to write the line to the file, but it adds the line, rather than overwriting the existing line:

sed -i  $line'i'"system.latitude=1.76011"  /tmp/system.cfg;
line=$(grep -n "latitude" /tmp/system.cfg |cut -f1 -d:); 

I have also tried using single and double quotes to no avail. Can someone point me in the direction of where I am going wrong.

如果我理解你的话,你可以保存grep|cut ,你的要求可以用(gnu)sed一次性完成:

sed -i '/latitude/s/.*/system.latitude=1.888888/' /tmp/system.cfg

Kent was absolutely correct when he mentioned about cutting the grep out of the equation completely. For anyone interested here is the final code using my method:

line=$(grep -n "latitude" /tmp/system.cfg |cut -f1 -d:); 
sed -i "${line}s/.*/system.latitude=1.999/" /tmp/system.cfg;

But I will be going with Kent's answer for the final implementation.

This is one of those issues where you commit to a process and complicate matters further as pointed out by Tom:

This is what is known as an XY problem. You have decided upon a process (find the line, store to a variable, etc.) and asked how to do that, rather than simply asking "how do I replace the whole line that matches a pattern". Well done to Kent for getting to the bottom of it. – Tom Fenech

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