2

I want to change a cell in file when my desired state exists. Example:

File:

id311    vmName1    state0
id312    vmName2    state0
id313    vmName3    state0

I will type a script and this script changes the state column of just one row. So if I type sed -i 's/state0/state1/g' all state0's be state1. I want to change state of only one row like:

File:

id311    vmName1    state0
id312    vmName2    state1
id313    vmName3    state0 

How can I use the sed command for a special line with use id? note: id's are unique.

3

Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/.

$ sed '1s/state0/XXXX/' file
id311    vmName1    XXXX
id312    vmName2    state0
id313    vmName3    state0

Since you want to edit in place, say:

sed -i.bak '1s/state0/XXXX/' file

Note I use .bak after the -i flag. This will perform the change in file itself but also will create a file.bak backup file with the current content of file before the change.


For a variable line number use the variable normally, as well as double quotes to have it expanded:

sed -i.bak "${lineNumber}s/state0/XXXX/" file
  • Thanks but it doesn't change the file I think so. I want to change line in the file. – Gefolge Aug 11 '17 at 8:36
  • 1
    @A.Guven just place the -i as your attempt shows. – fedorqui Aug 11 '17 at 8:37
  • Well, how can I use this with a variable like $lineNumber? – Gefolge Aug 11 '17 at 8:39
  • 1
    @A.Guven see update. – fedorqui Aug 11 '17 at 8:42
2

How can I use the sed command for a special line with use id? note: id's are unique.

Since ids are unique, it make sense to use the first field as a key:

sed -i '/id312/s/state0/state1/' file

You could want to create a command, and pass the id number and the file as parameters:

#!/usr/bin/env bash
sed -i "/id$1/s/state0/state1/" $2

invoking it like this:

./sed.sh 312 file

Note: Always be careful with the -i switch: test first without it.

  • thanks. but i cannot use parameter with a script. there is a bug on my platform i think so. but anyway your solution is true. thanks again. – Gefolge Aug 11 '17 at 15:33
  • i get the line number by using id with "cat -n" for now. – Gefolge Aug 11 '17 at 15:36
  • @A.Guven You can skip the intermediate passage about the line number and use the id as in the first example. – simlev Aug 11 '17 at 15:39
  • yeah right. sorry, my brain does not working right now :) – Gefolge Aug 11 '17 at 15:44

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.