简体   繁体   English

修改文件匹配WORD1和NOT WORD2(Sed / Awk)中的行

[英]Modify Line in File Matching WORD1 and NOT WORD2 (Sed/Awk)

I need to add kernel parameters to lines not already containing them. 我需要将内核参数添加到尚未包含它们的行中。 (Don't want to add it to all lines in case it's already there.) (如果已经存在,请不要将其添加到所有行。)

I've built this awk command to do it in buffer, but having trouble getting it into the file itself since awk lacks the ability to edit in place like sed . 我已经构建了这个awk命令来在缓冲区中执行它,但是因为awk缺乏像sed那样编辑的能力而无法将其放入文件本身。 (However I can't figure out how to do this type of match with sed .) (但我无法弄清楚如何与sed进行这种匹配。)

awk '/\\tkernel/&&!/audit=1/ { print $0" audit=1"; }' /etc/grub.conf

This looks for lines matching "kernel" and NOT "audit=1" (appending " audit=1" as necessary.) 这将查找匹配“kernel”和NOT “audit = 1”的行(必要时附加“audit = 1”。)

Tagged as sed/awk, but open to other suggestions. 标记为sed / awk,但对其他建议持开放态度。

使用sed:

sed -i '/kernel/{/audit=1/!s/$/ audit=1/}' /etc/grub.conf

The in-place editing functionality of sed uses a temporary file that without a suffix, is used to replace the existing file. sed的就地编辑功能使用没有后缀的临时文件来替换现有文件。 For example, this: 例如,这个:

sed -i '/\tkernel/ { /audit=1/!s/$/ audit=1/ }' /etc/grub.conf

is the same as this: 与此相同:

sed '/\tkernel/ { /audit=1/!s/$/ audit=1/ }' /etc/grub.conf > tmp && mv tmp /etc/grub.conf

The -i flag just sugar coats the process. -i标志只是糖涂层过程。 Therefore, you can simply apply the same logic to your awk command: 因此,您可以简单地将相同的逻辑应用于awk命令:

awk '/\tkernel/ && !/audit=1/ { print $0, "audit=1"; next }1' /etc/grub.conf > tmp && mv tmp /etc/grub.conf

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

相关问题 正则表达式+选择除word1或word2之外的所有内容 - regex + select everything but word1 or word2 Javascript RegEx的用法:从“ word1-word2”到“ word1-word2” - Javascript RegEx how to make:“word1—word2” to“word1 — word2” 需要一个匹配“word1,word2,word3”的正则表达式 - Need a regular expression that matches “word1, word2, word3” 用于匹配{word1 | word2}格式的文本的函数 - Function to match text in {word1|word2} format 如何替换“?” 来自?word1 word2? 与正则表达式 - How to replace '?' from ?word1 word2? with Regex 搜索查询的正则表达式,例如:word1 *(word2 -word3 -word4)* word5 - Regular expression for search query like: word1 * (word2 -word3 -word4) * word5 如何使用 sublime RegEx 将 word1 替换为<span>word1</span> ,将 word2 替换为<span>word2</span> ,将 n 替换为<span>n</span> ? - how can i replace word1 with <span>word1</span>,word2 with <span>word2</span>,n with <span>n</span> using sublime RegEx? 需要为除 word1 或 word2 之外的任何单词找到正则表达式 - Need to find a regular expression for any word except word1 or word2 匹配除从 word1 开始到 word2 结束的单词之外的所有内容 - Match everything except a selection of words starting from word1 and ending at word2 如何使用正则表达式捕获字符串“ word1 / word2 / *”? - How can I capture the string “word1/word2/*” with a regular expression?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM