943,708 Members | Top Members by Rank

Ad:
Jun 4th, 2008
0

Replacing string in nth line

Expand Post »
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
Reputation Points: 10
Solved Threads: 0
Newbie Poster
maxmave is offline Offline
2 posts
since Jun 2008
Jun 4th, 2008
0

Re: Replacing string in nth line

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
Reputation Points: 102
Solved Threads: 47
Posting Whiz
eggi is offline Offline
399 posts
since Oct 2007
Jun 4th, 2008
0

Re: Replacing string in nth line

if TEST2 is the second field and no where else and you want to replace only that second field,
Shell Scripting Syntax (Toggle Plain Text)
  1. awk 'NR==4{$2="DEV"}1' file
Reputation Points: 75
Solved Threads: 44
Junior Poster
ghostdog74 is offline Offline
156 posts
since Apr 2006

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Shell Scripting Forum Timeline: print first / last char from a file
Next Thread in Shell Scripting Forum Timeline: specify the current directory





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC