0

Suppose I want to replace a value in a file only once. My command is replacing it for all the matchin pattern. example

read -p "Enter the reference account name : " ACC
read -p "Enter the user name to be inserted into VISUDO : " UNAME
sed -i "s/\( *$ACC =*\)[^ ]*\(.*\)*$/\1 $UNAME,\2/" sudo_file.txt

File is

User_Alias  USERS1 = user1
Runas_Alias  APP =  oozie
Cmnd_Alias SU_APP = /bin/su - oozie
USERS1   ALL = (root) SU_APP
USERS1   ALL = (APP) ALL

when m running its replacing all the values USER1 in the above file. I want the output as

User_Alias  USERS1 = user1, user2, user3 

Only for this line and not for other two USER1 appearing in the file.

Where ACC is USER1 and UNAME is "user1" or "user2" or "user3" etc

choroba
  • 231,213
  • 25
  • 204
  • 289
shaheer01
  • 111
  • 2
  • 11

3 Answers3

1

You can use branching in sed:

for i in {1..20} ; do
    echo $i
done | sed 's/2/TWO/; te; b; :e {n;be}'

2 gets replaced by TWO, then t branches to e, which reads in the following line with n and goes again to e. Before the match, te does nothing, so b skips to the end of the script and the next line is processed.

choroba
  • 231,213
  • 25
  • 204
  • 289
0

You can perform a replacement only once by keeping a counter:

awk '/pattern/ && !c {sub("find", "replace") && c=1}1' file

That is, look for the pattern and perform the substitution just in case it did not happen before. In such case, try to perform it and set the counter if it was done.

Example

$ cat file
hello man
hello there
hello you
hello there
$ awk '/hello/ && !c {sub("here", "XXX") && c=1}1' file
hello man
hello tXXX
hello you
hello there
fedorqui
  • 275,237
  • 103
  • 548
  • 598
0

This has been answered before here

Your sed command can be something like below (I have verified that below command is working on your provided sudo_file content):

sed "0,/User_Alias/{s/\( *$ACC =*\)[^ ]*\(.*\)*$/\1 $UNAME,\2/}" sudo_file.txt
Community
  • 1
  • 1
Umair A. Shahid
  • 134
  • 1
  • 4