Jaime
Jaime

Reputation: 21

How to create text file in a directory and add text to it in one command from terminal

I'm doing an assignment on terminal commands in Ubuntu. The problem I'm currently stuck on asks me to create a text file in a directory I'm not currently in, and add text to it, all using one command. I was trying to run it as:

touch /home/user/Desktop/index.html
echo "text" > index.html
...

but keep getting errors.

Upvotes: 1

Views: 9359

Answers (3)

Kyo
Kyo

Reputation: 101

Also you can use printf:

printf 'Hello\nworld' > /home/user/Desktop/index.html

Upvotes: 2

user2849202
user2849202

Reputation:

cat > /the/directory/your_file
hello world!
foo bar
baz
^D

comments:

  • the part between cat... and ^D is text you enter.
  • ^D (control-D) is an End-of-File marker you type to tell the program, cat, that that is the end of the file you just created, your_file.
  • If you now do cat /the/directory/your_file, (NOTE: no redirection operator '>' here!), you will see the contents of the file you just created.
  • Be sure to type only one ^D (control-D); if you hit it twice you will find yourself logged out from the terminal...; the second ^D went to your terminal and told it 'End-of-File', which to it means, bye bye, aka. 'exit'.

Upvotes: 1

altermetax
altermetax

Reputation: 706

You also need to specify the path when writing "text" into the file:

touch /home/user/Desktop/index.html ; echo "text" > /home/user/Desktop/index.html

Also, there's no need to touch the file first. The > operator will automatically create the file if it doesn't exist, so you can just type:

echo "text" > /home/user/Desktop/index.html

Upvotes: 3

Related Questions