Using sed command for a specific line

2

1

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.

Gefolge

Posted 2017-08-11T07:51:15.537

Reputation: 555

Answers

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

fedorqui

Posted 2017-08-11T07:51:15.537

Reputation: 1 517

Thanks but it doesn't change the file I think so. I want to change line in the file. – Gefolge – 2017-08-11T08:36:47.957

1@A.Guven just place the -i as your attempt shows. – fedorqui – 2017-08-11T08:37:10.330

Well, how can I use this with a variable like $lineNumber? – Gefolge – 2017-08-11T08:39:41.557

1@A.Guven see update. – fedorqui – 2017-08-11T08:42:12.577

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.

simlev

Posted 2017-08-11T07:51:15.537

Reputation: 3 184

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 – 2017-08-11T15:33:26.660

i get the line number by using id with "cat -n" for now. – Gefolge – 2017-08-11T15:36:20.683

@A.Guven You can skip the intermediate passage about the line number and use the id as in the first example. – simlev – 2017-08-11T15:39:40.497

yeah right. sorry, my brain does not working right now :) – Gefolge – 2017-08-11T15:44:03.897