使用 sed - shell 脚本将文本附加到行尾

Appending text to end of line with sed - shell script

我有一个简单的 shell 脚本,几乎可以正常工作了。

要求:

到目前为止,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
...
...

通过将 sed 标志从 -e > -i 更改并删除 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

sed 对于特殊字符可能会比较困难。在这种情况下,您可以使用 &,什么将被替换为他完成的匹配字符串。

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