Issue
I've got a simple shell script that I almost have working as desired.
Requirements:
- Read file names in dir into an array
- 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
...
...
Solution
sed
can be difficult with special characters. 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
Answered By - Walter A Answer Checked By - Katrina (WPSolving Volunteer)