The reason why you are getting this result is because you don't apply the sed
command to the file directly, but to the result of a command substitution.
This means that the text processing is not actually applied to
DB_USER=myusername
DB_PASS=mypassword
DB_NAME=mydatabase
but to the result of the cat
command applied to the file content, after an unquoted command substitution that squeezes the lines.
If you try
echo $(cat /root/dadosDB)
you will notice that the output is
DB_USER=myusername DB_PASS=mypassword DB_NAME=mydatabase
all on a single line, rather than on separate lines. If you place the command substitution in double-quotes, as in
echo "$(cat /root/datosDB)"
the newlines will be preserved.
The key points are that
- you need neither the
cat
nor the command substitution, and
- if you use the command substitution without placing it in double-quotes, you will lose the newlines (see this Q&A e.g.).(1)
TL;DR:
Use
sed -n -e 's/^.*DB_PASS=//p' /root/dadosDB
or (rather)
sed -n -e 's/^DB_PASS=//p' /root/dadosDB
to exclude lines with keywords that start differently, but end in DB_PASS
.
Please note: You write "and stop at that line, ignoring the following ones." I took this as meaning that you want to print the word after DB_PASS
, but not the following lines (that technically also come after DB_PASS
. If you mean that there could be more lines starting with DB_PASS
and you want to ensure matching only the first, you will need a slight adjustment:
sed -n -e '0,/DB_PASS/s/^DB_PASS=//p' /root/dadosDB
(1) Note that the issue in your particular case is how your shell (I assume Bash) handles "Here-strings" with unquoted substitutions, so (as noted by @steeldriver) a better demonstration is
cat <<< "$(cat /root/dadosDB)"
vs.
cat <<< $(cat /root/dadosDB)
The behavior has changed with Bash v4.4: Before, the output of the two commands was different in the same way as the echo
examples mentioned above. In later versions of Bash, the unquoted command substitution would no longer lead to word-splitting and consequent squeezing of multi-line output.
If you are interested to learn more, you may want to look at
Also, I would recommend checking your scripts with shellcheck
, also available as standalone tool on many Linux distributions, to avoid syntax (and other) errors.
stop at that line, ignoring the following ones
? None of the current answers do that, they all continue to read the rest of the file after finding the matching line so - do you require that because your file is particularly huge or because there might be a secondDB_PASS=mypassword
line that you don't want matched or something else? Or do you actually not need that at all? – Ed Morton Sep 28 '21 at 14:47