检查多行并在末尾添加字符串

时间:2016-11-16 21:16:44

标签: linux bash shell

我试图编写一个脚本来检查/boot/grub/grub.conf的内容,以查找以" kernel"开头的每一行。如果它不包括" nousb"在该行中,它会将其添加到最后。

默认情况下,我的grub.conf有两行内核,我的脚本第一次运行并应用" nousb"到两行的末尾。但是,为了测试我从第一行删除nousb并将其保留在第二行的情况,我的脚本会认为它已应用于这两行而不是重新应用于第一行#n失踪。这就是我所拥有的

grep -w 'nousb' /boot/grub/grub.conf || sudo sed -i '/^\s*kernel/ s/$/ nousb/' /boot/grub/grub.conf

我希望添加' nousb'无论已经有多少行,任何以内核开头的行都会丢失它。有什么想法吗?

为了展示,我上面的脚本会将nousb添加到文件中的两行中,并带有以下内容:

kernel word1 word2
kernel word3 word4

但不是这样:

kernel word1 word2
kernel word3 word4 nousb

3 个答案:

答案 0 :(得分:1)

使用GNU sed:

sed '/\bkernel\b/{/\bnousb\b/b;s/$/ nousb/}' file
  

\b:标记字边界

     

b:分支到脚本结尾

     

$:标记行尾

答案 1 :(得分:0)

以下似乎有效:

#!/bin/bash
while read -r line ; do
    shopt -s extglob
    if [[ $line == kernel* && $line != *' 'nousb@(' '*|) ]] ; then
        line+=' nousb'
    fi
    printf '%s\n' "$line"
done

条件检查$linekernel加空格开头,并且不包含nousb前面有空格,后跟空格或行尾。您可以使用它来创建新文件,然后用它替换旧文件:

cp input-file input-file.backup
./script.sh input-file > new-file
mv new-file > input-file

答案 2 :(得分:0)

使用awk非常简单:

awk '$1=="kernel" && !/\<nousb\>/{$0 = $0 OFS "nousb"} 1' file

kernel word1 word2 nousb
kernel word3 word4 nousb
  • $1=="kernel"检查第一个单词是否为kernel
  • !/\<nousb\>/检查当前行是否没有完整的单词nosub
  • $0 = $0 OFS "nousb"在当前行的末尾添加nosub
  • 1是打印每一行的默认操作