Create and edit text files

To create file, we can use several aproach. By using cat and ctrl+d to exit and save the content or describe string endpoint to close the session and save its content, for example I use EOF.

[root@1305ce547374 textfile]# touch test1.txt
[root@1305ce547374 textfile]# ls -lh test1.txt 
-rw-r--r--. 1 root root 0 Feb 18 21:07 test1.txt

[root@1305ce547374 textfile]# echo "hello world" > test2.txt
[root@1305ce547374 textfile]# ls -lh test2.txt 
-rw-r--r--. 1 root root 12 Feb 18 21:08 test2.txt

[root@1305ce547374 textfile]# cat > test3.txt
hello world
[root@1305ce547374 textfile]# ls -lh test3.txt 
-rw-r--r--. 1 root root 12 Feb 18 21:08 test3.txt

[root@1305ce547374 textfile]# cat > test4.txt << EOF
> hello world
> EOF
[root@1305ce547374 textfile]# ls -lh test4.txt 
-rw-r--r--. 1 root root 12 Feb 18 21:09 test4.txt

We see that touch command only create an empty file

[root@1305ce547374 textfile]# ls -lh
total 12K
-rw-r--r--. 1 root root  0 Feb 18 21:07 test1.txt
-rw-r--r--. 1 root root 12 Feb 18 21:08 test2.txt
-rw-r--r--. 1 root root 12 Feb 18 21:08 test3.txt
-rw-r--r--. 1 root root 12 Feb 18 21:09 test4.txt

We could also create a file by open a text editor and define the file name after the command, for instance vi test8.txt or nano test9.txt

Edit file

To edit file, we can use vi or vim and nano. Make sure the text editor has installed

[root@1305ce547374 textfile]# vi test1.txt 
[root@1305ce547374 textfile]# nano test2.txt 

To close vi session/buffer, make sure we are not in insert mode by press esc then write :q! for quit or :wq to write the content and quit. To close nano editor, press Ctrl+x. Two save the content press Ctrl+o.

I prefer vi for its versatility. I write this blog using vi, push into git and auto published here.


This material is refers to the rhca objectives