【问题标题】:Appending text to end of line with sed - shell script使用 sed - shell 脚本将文本附加到行尾
【发布时间】:2019-07-06 15:14:37
【问题描述】:

我有一个简单的 shell 脚本,我几乎可以按要求工作。

要求:

  • 将 dir 中的文件名读入数组中
  • 遍历文件并将文本附加到匹配行的末尾

到目前为止,req one 已经实现,但我似乎无法让 sed 正确附加到一行。

例如,这是我的脚本:

#!/bin/bash

shopt -s nullglob
FILES=(/etc/openvpn/TorGuard.*)
TMPFILES=()

if [[ ${#FILES[@]} -ne 0 ]]; then
    echo "####### Files Found #######"
    for file in "${FILES[@]}"; do
        echo "Modifying $file.."
        line=$(grep -n "auth-user-pass" "$file" | cut -d: -f -1)
        array=($(sed -e $line's/$/ creds.txt &/' "$file"))
        tmp="${file/.conf/.ovpn}"
        echo "$tmp created.."
        TMPFILES+=("$tmp")
        printf "%s\n" "${array[@]}" > ${tmp}
    done
fi

预期输出:

....
....
auth-user-pass creds.txt
...
...

收到的输出:

...
...
auth-user-pass
creds.txt
...
...

【问题讨论】:

  • 换行符由printf 插入。 sed 中的 & 仅应在调用匹配的字符串时使用。 $(行尾)不会消失。
  • 所以说真的,你的问题是为什么echo "auth-user-pass" | sed 's/$/ creds.txt &/' "$file 不起作用;-)? -e 几乎总是多余的。说到多余,捕获$line(lineNum?)如果有 2 行或更多行匹配,您的脚本会发生什么?你根本不需要那个处理。如果您希望所有行都处理使用sed cmd,正如我首先指出的那样,如果您只想修复第一次出现,那么sed /....../q(q 表示退出)将满足您的需求。祝您好运。

标签: bash sed debian


【解决方案1】:

sed 可能很难使用特殊字符。在这种情况下,您可以使用&,它将替换为他完成的匹配字符串。

for file in "${FILES[@]}"; do
    echo "Modifying ${file}.."
    sed -i 's/.*auth-user-pass.*/& creds.txt/' "${file}"
done

【讨论】:

    【解决方案2】:

    通过从 -e > -i 更改 sed 标志解决了该问题,并删除了 tmp 文件的使用并使用 sed 进行:

    #!/bin/bash
    
    shopt -s nullglob
    FILES=(/etc/openvpn/TorGuard.*)
    
    if [[ ${#FILES[@]} -ne 0 ]]; then
        echo "####### Files Found #######"
        for file in "${FILES[@]}"; do
            echo "Modifying $file.."
            line=$(grep -n "auth-user-pass" "$file" | cut -d: -f -1)
            sed -i $line's/$/ creds.txt &/' "$file"
        done
    fi
    

    【讨论】:

    • 您的grep | cut; sed 等仅相当于sed '/auth-user-pass/ s/$/ creds.txt /'@WalterA's solution
    猜你喜欢
    • 2013-10-20
    • 2014-04-12
    • 2011-07-31
    • 2022-08-17
    • 2011-03-08
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    • 2020-07-12
    相关资源
    最近更新 更多