简体   繁体   English

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

[英]Appending text to end of line with sed - shell script

I've got a simple shell script that I almost have working as desired. 我有一个简单的shell脚本,几乎可以按需工作了。

Requirements: 要求:

  • Read file names in dir into an array 将dir中的文件名读入数组
  • iterate through the files and append text to the end of a matching line 遍历文件并将文本附加到匹配行的末尾

So far req one is achieved however, I cannot seem to get sed to append properly to a line. 到目前为止,已达到要求,但似乎无法正确地将其附加到一行。

For example here's my script: 例如,这是我的脚本:

#!/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

Expected output: 预期产量:

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

Received output: 收到的输出:

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

sed can be difficult with special characters. 使用特殊字符可能很难实现sed In this case you might use & , what will be replaced by he completed matched string. 在这种情况下,您可以使用& ,将由他完成的匹配字符串替换。

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

Resolved the issue by changing the sed flag from -e > -i and removed the use of tmp files and do it with sed: 通过从-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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM