Create/modify files

Instructor note

Total: 30min (Teaching: 25Min | Discussion:0min | Breaks:0min | Exercises:0Min| Type-along-pause:5 min)

Prerequisites

  • Should be logged in to one of the HPC systems

Objectives

  • Questions

    • How to create or modify text files without leaving the terminal

    • What is terminal text editor ?

    • How to view a file content

  • keypoints

    • echo redirection

    • cat

    • nano editor

Create files with echo redirection

The command echo is used to display contents on terminal window. By using redirection we can store the content in a file instead of displaying it.

# Using echo to create a file. NB: if there is already content in `new-file-with-echo.txt`
# this will be overwritten
[MY_USER_NAME@CLUSTER_NAME ~]$ echo "Created with echo" > new-file-with-echo.txt 
# Append content to a file using echo together with two less-than signs   
[MY_USER_NAME@CLUSTER_NAME ~]$ echo "Last line added with echo" >> new-file-with-echo.txt 

Danger

NB! The > will overwrite any contents in the file.

If you want instead to append make sure to use >>

Create files with cat

cat can be used to create a file in addition to be used to view content (which we learned in Moving around and looking at things). cat can create files by typing in content or by using the content of one or more files. As with other bash commands, cat can be combined with other commands to achieve complex tasks.

# Create a file
[MY_USER_NAME@CLUSTER_NAME ~]$ cat > new-file-with-cat.txt 
A
B
C

# CTRL + D to stop adding content and end the operation.
# Create a file using the content from two other files
[MY_USER_NAME@CLUSTER_NAME ~]$ cat file1 file2 > combined-content

Using a text editor

We can use Visual Studio Code to display, create, edit, and delete files on a remote machine. Logging in to the remote machine using the Remote - SSH extension allows you to open a folder on the remote machine and work on files as if they were stored locally on your machine.

  1. Click the Explorer icon in the left sidebar to open the Explorer view. explorer_icon

  2. A menu should open on the left side of the screen. Click the Open Folder button to open a folder on the remote machine.

explorer_open_folder

  1. Select a folder on the remote machine to open. The home directory, /cluster/home/USERNAME, should be the default option. You may be asked if you trust the authors of the files in the folder. Click Yes to trust the authors and open the folder.

remote_open

  1. Now that your home folder is open, you can create, edit, and delete files as if they were stored locally on your machine. The left sidebar shows the contents of the opened directory. You can create a new file by clicking the New File button at the top of the sidebar. new_file

remote_file_opened