1

I would like to replace from line number 4, the character "K" which is right after 19823 but not the "K" character which follows

19822SOL     OW60021   7.173   
19822SOL    HW160022   7.230   
19822SOL    HW260023   7.124   
19823K        K60024   8.427   

so the new file should look like

19822SOL     OW60021   7.173   
19822SOL    HW160022   7.230   
19822SOL    HW260023   7.124   
19823exc      K60024   8.427   

currently i do know how to use sed command to replace K from line 4 with exc such as

sed -i "4s/K/exc/g" <newfile> 

but I do not know how to specify which column to select

  • I can use sed -i "4s/19823K /19823exc/g" <newfile> but I want to avoid this ideally – Dimitris Mintis Dec 9 '18 at 22:30
  • OK, so you don't want to change a K that occurs after a 19823; you want to change a K that occurs in the first column of line 4. Or do you want to change all the Ks that occur in the first column of line 4? Or do you want to change a K that occurs in a specified column of line 4 (or some other specified line)? The simple solution of leaving off the g doesn't help if you want to manipulate a column other than the first. – G-Man Dec 10 '18 at 1:14
3

If it's just about that particular K, then getting rid of the g flag will do, as sed will only replace K once. Thus:

sed -i "4s/K/exc/" <newfile> 

Namely, it replaces the first appearance of K with exc on line 4.

1

If you want the first K, just get rid of the g flag:

sed -i '4s/K/exc/' <newfile> 

If you want to replace the 2nd, 3rd, etc. K, use 2, 3, 4 instead of g

sed -i '4s/K/exc/2' <newfile>
sed -i '4s/K/exc/3' <newfile>

If you want to replace all Ks from the 3rd up to the end (only supported with GNU sed):

echo 'KKKKKK' | sed s/K/E/3g
KKEEEE

And btw, don't use double quotes (") unless you really want to insert shell variables, command expansions, etc in the string passed to sed.

  • Note that using both a number and g as flags to the substitute command requires GNU sed. – Kusalananda Dec 15 '18 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.