LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   append text in new or old text file methods (https://www.linuxquestions.org/questions/linux-newbie-8/append-text-in-new-or-old-text-file-methods-4175628922/)

anon297 05-03-2018 02:27 AM

append text in new or old text file methods
 
Dear Mentors :cool:
I'm quite Newbie here!
And Thanks for your help every day!

Today, I have a question about creating a new file or append some text to an old file.

I know there are two methods.

First, 'echo'
Code:

$echo 'something to write' > file.txt
Second, 'cat > file.txt << "EOF"
Code:

$cat > file.txt << "EOF"
something to write
EOF

Which one do you prefer? or What advantage and disadvantage each method have?

Thanks for your help again!

Turbocapitalist 05-03-2018 02:43 AM

Why do you ask?

I'd add that actually there are at least four methods.

Third,

Code:

$ echo 'something to write' | tee file.txt
Fourth,

Code:

$ cat | tee file.txt  << "EOF"
something to write
EOF

The even-numbered ones as listed above are using Here Documents. What have you learned of them so far?

anon297 05-03-2018 02:48 AM

Quote:

Originally Posted by Turbocapitalist (Post 5850043)
Why do you ask?

Oh! I'm just wondering if there are some recommended situations to use specific method.
If not, I can use anything.

fatmac 05-03-2018 03:07 AM

Be careful with the redirectors, a single > creates or overwrites what was there before, whilst a double >> adds to it. ;)

Edit: I usually need to add something to a file, like a config file, so my most used is the >>.

Turbocapitalist 05-03-2018 03:17 AM

Pretty much you can use anything. echo is good for short texts. tee is good if you have to write as another user because sudo can be locked down to allow writing to just that one file.

Code:

$ echo "something to write" | sudo -u anotheruser tee /path/to/some/file.txt
See "man sudo", "man sudoers", and "man tee" You can set tee to append if you like.

The Here Documents are good for when you have a lot of text on multiple lines. Pay attention to quotes. Notice that you used double quotes in your example. They are different from single quotes.

Code:

$ echo 'something from $USER' > file.txt
$ echo "something from $USER" > file.txt

$ cat > file.txt << 'EOF'
something to write from $USER
EOF
$ cat > file.txt << EOF
something to write from $USER
EOF


syg00 05-03-2018 03:29 AM

I long ago learnt there is rarely a "best" method in Linux.
So many smart people contributing, new options (maybe better) keep appearing.

xamaco 05-03-2018 06:01 AM

Code:

cat > file.txt
is enough, just end input with a Ctrl-D


All times are GMT -5. The time now is 04:01 PM.