简体   繁体   English

sed命令仅在文件中替换一次值

[英]Sed command to replace a value only once in a file

Suppose I want to replace a value in a file only once. 假设我只想替换一次文件中的值。 My command is replacing it for all the matchin pattern. 我的命令是将其替换为所有matchin模式。 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. 当m运行时,替换上面文件中的所有USER1值。 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. 仅用于此行,而不用于文件中出现的其他两个USER1

Where ACC is USER1 and UNAME is "user1" or "user2" or "user3" etc 其中ACC为USER1,UNAME为“ user1”或“ user2”或“ user3”等

You can use branching in sed : 您可以在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 . 2被两个替换,然后t分支到e ,在下一行用n读取并再次到e Before the match, te does nothing, so b skips to the end of the script and the next line is processed. 比赛之前, te不执行任何操作,因此b跳到脚本的结尾并处理下一行。

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

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命令可以类似于以下内容(我已经验证了以下命令正在处理您提供的sudo_file内容):

sed "0,/User_Alias/{s/\( *$ACC =*\)[^ ]*\(.*\)*$/\1 $UNAME,\2/}" sudo_file.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM