Celeb Glow
general | March 07, 2026

Using sed command for a specific line

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.

2 Answers

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
4

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.

4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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