Hello All,

How to replace a string in nth line of a file using sed or awk.

For Ex: test.txt

Line 1 : TEST1 TEST2 TEST3
Line 2 : TEST1 TEST2 TEST3 TEST4
Line 3 : TEST1 TEST2 TEST3 TEST5
Line 4 : TEST1 TEST2 TEST3 TEST6
Line 5 : TEST1 TEST2 TEST3 TEST7

i want to go to 4th line of a file and replace the word TEST2 in that line with the word DEV2.

any suggestions will be helpful.

Thanks

Rahul

Hey There,

For sed, you can just specify the line number, like substituting THIS for THAT on line 4:

sed 4s/THIS/THAT/

In Awk, I believe you can specify the NR variable to cherry-pick the line.

Best wishes,

MIke

if TEST2 is the second field and no where else and you want to replace only that second field,

awk 'NR==4{$2="DEV"}1' file
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.