【发布时间】: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 行或更多行匹配,您的脚本会发生什么?你根本不需要那个处理。如果您希望所有行都处理使用sedcmd,正如我首先指出的那样,如果您只想修复第一次出现,那么sed /....../q(q 表示退出)将满足您的需求。祝您好运。