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

时间:2019-07-06 15:14:37

标签: bash sed debian

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

要求:

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

但是,到目前为止已经实现了一个要求,我似乎无法将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
...
...

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

通过从-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