What will be an "elegant" one-line way to append a single line of data into the end of a file, with herestring, if this exact data isn't already in that file?
This is my herestring append pattern:
cat >> /var/www/html/myFile <<< "myOutput"
What will be an "elegant" one-line way to append a single line of data into the end of a file, with herestring, if this exact data isn't already in that file?
This is my herestring append pattern:
cat >> /var/www/html/myFile <<< "myOutput"
Assuming that you want "myOutput" to be a full line at the last line of the file:
s="myOutput"; sed '$ {/^'"$s"'$/b; s/$/\n'"$s"'/}' file
s="myOutput"
Set pattern to match
sed
use sed
$ {…}' file
On the last line of the file
/^'"$s"'$/b
Match the pattern as a whole line and branch to end if matched.
s/$/\n'"$s"'/
If no match, append the pattern at the end line.
If the file already contains the "myOutput" data somewhere other than the last line, this will add another copy of it at the end of the file.
sed -i
. (2) Your command doesn’t work when the text string contains a slash.
Jan 17, 2018 at 23:48
In below script will check in complete last line for whether variable i present or not if not it inserts variable i in last line of file.
As tested it worked fine
#!bin/bash
i="praveen"
f=$(sed -n '$p' p.txt | sed -n "/^$i$/p")
if [[ -z $f ]]
then
sed "\$s/.*/&\n$i/g" p.txt
else
echo "output exsists"
fi
/
at the beginning of the interpreter name (after the #!
). (3) s/$/\nfoo/
(which isaac’s answer uses) is a somewhat awkward way to add a line of text (containing “foo”) to a file in sed
. (As I’m sure you understand, … (Cont’d)
Jan 17, 2018 at 23:44
$
at the beginning of that command (before the s
) represents the last line of the file, and says “do this at the end of the file”.) s/.*/&\nfoo/
(which your answer uses) is an unnecessarily complicated version of the same command. But isaac’s answer uses that awkward technique because he’s trying to solve the problem economically (i.e., in one line) and he’s using sed
already. Your use of it in a standalone command (the sixth line of your script) is doubly unnecessarily complicated and unintuitive, because, in that context, you don’t need to be using sed
. … (Cont’d)
Jan 17, 2018 at 23:44
cat >> "$file" <<< "$i"
— or, better yet, something like Stéphane’s version: printf "%s\n" "$i" >> "$file"
. (4) The question asks how to append a line of text to a file. Your answer doesn’t even accomplish that (although, to be fair, isaac’s doesn’t either). To append a line of text to a file using your command, you would need to use sed -i
. (5) Your command doesn’t work when the text string contains a slash.
Jan 17, 2018 at 23:44