简体   繁体   中英

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.

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

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'.

Also you can use printf :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM