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 Code:
$cat > file.txt << "EOF" Thanks for your help again! |
Why do you ask?
I'd add that actually there are at least four methods. Third, Code:
$ echo 'something to write' | tee file.txt Code:
$ cat | tee file.txt << "EOF" |
Quote:
If not, I can use anything. |
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 >>. |
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 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 |
I long ago learnt there is rarely a "best" method in Linux.
So many smart people contributing, new options (maybe better) keep appearing. |
Code:
cat > file.txt |
All times are GMT -5. The time now is 04:01 PM. |