sed命令删除单词的首次出现 [英] sed command to remove first occurrence of a word
问题描述
我想知道如何删除文件中第一个出现的单词.
I want to know how to remove the first occurrence of a word in a file.
示例:我只想从第一次出现时删除管理员.
Example: I want to remove the admin, from the first occurrence only.
account required pam_opendirectory.so
account sufficient pam_self.so
account required pam_group.so no_warn group=admin,wheel fail_safe
account required pam_group.so no_warn deny group=admin,wheel ruser fail_safe
我尝试过:
sudo sed -i.bak "s/admin,//1" /etc/pam.d/screensaver
但这可以消除这两种情况,有什么主意吗?
But that removes both cases, any ideas?
推荐答案
使用sed
要删除文件中的第一个匹配项:
Using sed
To remove the first occurrence in the file:
$ sed -e ':a' -e '$!{N;ba;}' -e 's/admin,//1' file
account required pam_opendirectory.so
account sufficient pam_self.so
account required pam_group.so no_warn group=wheel fail_safe
account required pam_group.so no_warn deny group=admin,wheel ruser fail_safe
(以上已使用GNU sed进行了测试.)
(The above was tested with GNU sed.)
-
-e ':a' -e '$!{N;ba;}'
这一次将整个文件读入模式空间. (如果文件太大而无法存储,则不是一个好方法.)
This reads the whole file in at once to the pattern space. (If your file is too large for memory, this is not a good approach.)
-e 's/admin,//1'
这将在第一次出现的admin
和仅第一次出现的地方执行替换.
This performs the substitution on the first occurrence of admin
and only the first occurrence.
Wintermute报告BSD sed不能单行执行分支指令,并建议使用此替代方法来更改文件:
Wintermute reports that BSD sed cannot do branch instructions in one-liners and suggests this alternative for changing the file in place:
sed -i.bak -n '1h; 1!H; $ { x; s/admin,//; p; }' file
这一次读取整个文件,然后在读取最后一行后进行替换.
This reads the whole file in at once and then does the substitution once the last line has been read.
详细信息:
-
-n
默认情况下,sed将打印每一行.这可以关闭.
By default, sed would print each line. This turns that off.
1h
这会将第一行放在保留缓冲区中.
This places the first line in the hold buffer.
1!H
对于所有后续行,此附加将它们添加到保留缓冲区.
For all subsequent lines, this appends them to the hold buffer.
$ { x; s/admin,//; p; }
对于最后一行($),这将交换保留和模式缓冲区,以便模式缓冲区现在具有完整的文件. s/admin,//
进行替换,p
打印结果.
For the last line ($), this exchanges the hold and pattern buffer so that the pattern buffer now has the complete file. s/admin,//
does the substitution and p
prints the result.
$ awk '/admin/ && !f{sub(/admin,/, ""); f=1} 1' file >file.tmp && mv file.tmp file
结果是:
account required pam_opendirectory.so
account sufficient pam_self.so
account required pam_group.so no_warn group=wheel fail_safe
account required pam_group.so no_warn deny group=admin,wheel ruser fail_safe
工作原理
-
/admin,/ && !f{sub(/admin,/, ""); f=1}
对于每行,请检查它是否包含单词
admin,
,以及标志f
是否仍具有默认值零.如果是这样,请删除第一次出现的admin,
并将该标志设置为一个.For each line, check to see if it contains the word
admin,
and if the flagf
still has its default value of zero. If so, remove the first occurrence ofadmin,
and set the flag to one.1
打印每一行.
1
是awk的{print $0}
的简写.Print each line.
1
is awk's cryptic shorthand for{print $0}
.这篇关于sed命令删除单词的首次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!