首页 > 解决方案 > 使用 sed - shell 脚本将文本附加到行尾

问题描述

我有一个简单的 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
...
...

标签: bashseddebian

解决方案


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

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

推荐阅读