Solaris - 从文件注释特定行并添加新行

时间:2015-07-16 15:47:10

标签: bash text awk sed solaris

我还没有和solaris一起工作,但是我应该编写一个脚本来搜索文件中的一行,将其注释掉,并在其下面写下正确的行。

for i  in `cat solarishosts`
do
    #print hostname
    echo ${i}

    #get the line number of the expression after the /; save its value to linenum
    linenum="$(ssh -o ConnectTimeout=1 -o ConnectionAttempts=1 ${i} "awk '/%sugrp ALL=\(user\) lines: /usr/bin/su -, /usr/bin/su - user/a{ print NR; exit }' /usr/local/etc/sudoers")"

    #overwrite the line @ linenum (overwriting just a to add a comment)
    ssh -o ConnectTimeout=1 -o ConnectionAttempts=1 ${i} "sed -n "${linenum}"p <<< "#%sugrp ALL=\(user\) lines: /usr/bin/su -, /usr/bin/su - user""

    #use the linenum var to make a newlinenum var , this one being one line down from where the commented text was written
    newlinenum=linenum+1

    #write the line in quotes @ the newlinenum position
    ssh -o ConnectTimeout=1 -o ConnectionAttempts=1 ${i} "sed -n "${newlinenum}"p <<< "%sugrp ALL=\(ALL\) ALL""

done

我得到了奇怪的错误:

awk: syntax error near line 1
awk: bailing out near line 1
bash: -c: line 0: syntax error near unexpected token `newline'
bash: -c: line 0: `sed -n p <<< #%sugrp ALL=(user) PASSWD: /usr/bin/su -, /usr/bin/su - user'
bash: -c: line 0: syntax error near unexpected token `('
bash: -c: line 0: `sed -n linenum+1p <<< %sugrp ALL=(ALL) ALL'
  1. 我的awk语法看起来有错误......但是它不在第1行?而且我不确定错误是什么

  2. 我的第一个sed系列中的任何地方都没有换行符?

  3. 在我的代码中,我逃脱了&#34;(&#39;它抱怨

1 个答案:

答案 0 :(得分:1)

那太乱了。你不需要3次进入盒子。你的报价是个大问题。而且您实际上从未将更改写回文件。

试试这个:建立远程命令并调用ssh一次:

line='%sugrp ALL=(user) lines: /usr/bin/su -, /usr/bin/su - user'
newline='%sugrp ALL=(ALL) ALL'
file=/usr/local/etc/sudoers

awkcmd='$0 == line {print "#" $0; print new}'
cmd=$(
    printf "awk -v line='%s' -v new='%s' '%s' %s > %s.new && mv %s %s.bak && mv %s.new %s" \
        "$line" \
        "$newline" \
        "$awkcmd" \
        "$file" "$file" "$file" "$file" "$file" "$file"
)

while read -r host; do
    echo "$host"
    # perform the remote command
    ssh -o ConnectTimeout=1 -o ConnectionAttempts=1 "$host" sh -c "$cmd"

done < solarishosts

我尽可能使用单引号来减少常量字符串中反斜杠的需要,并且在使用时引用所有变量。