3 Week 2-Working With Files
Welcome to week 2! In this session we will be going over more tools to help us navigate our file system, view and manipulate files, and write basic scripts with bash/unix.
- Questions:
- How can I view and search file contents?
- How can I create, copy and delete files and directories?
- How can I control who has permission to modify a file?
- How can I repeat recently used commands?
- Objectives:
- View, search within, copy, move, and rename files. Create new directories.
- Use wildcards (
*) to perform operations on multiple files. - Make a file read only.
- Use the
historycommand to view and repeat recently used commands.
Before we start we need to download our data. The data for each week will be in a .tar.gz file that we will uncompress into our MarineGenomics Directory.
$ cd /home/exouser/
$ wget https://raw.githubusercontent.com/BayLab/MarineGenomicsData/main/week2_quarter.tar.gz
# use tar to uncompress the file
$ tar -xzvf week2_quarter.tar.gz3.1 Our data set: FASTQ files
Now that we know how to navigate around our directory structure, let’s
start working with our sequencing files. We did a sequencing experiment and
have two results files, which are stored in our untrimmed_fastq directory.
3.2 Wildcards
Navigate to your untrimmed_fastq directory:
$ cd ~/MarineGenomicsData/Week2/untrimmed_fastqWe are interested in looking at the FASTQ files in this directory. We can list all files with the .fastq extension using the command:
$ ls *.fastqSRR097977.fastq SRR098026.fastqThe * character is a special type of character called a wildcard, which can be used to represent any type of character.
Thus, *.fastq matches every file that ends with .fastq.
This command:
$ ls *977.fastqSRR097977.fastqlists only the file that ends with 977.fastq.
This command:
$ ls /usr/bin/*.sh/usr/bin/gettext.sh /usr/bin/nvidia-bug-report.sh /usr/bin/rescan-scsi-bus.shLists every file in /usr/bin that ends in the characters .sh.
Note that the output displays full paths to files, since
each result starts with /.
Exercise
Do each of the following tasks from your current directory using a single
lscommand for each:
- List all of the files in
/usr/binthat start with the letter ‘c’- List all of the files in
/usr/binthat contain the letter ‘a’- List all of the files in
/usr/binthat end with the letter ‘o’Bonus: List all of the files in
/usr/binthat contain the letter ‘a’ or the letter ‘c’Hint: The bonus question requires a Unix wildcard that we haven’t talked about yet. Try searching the internet for information about Unix wildcards to find what you need to solve the bonus problem.
Exercise
echois a built-in shell command that writes its arguments, like a line of text to a standard output. Theechocommand can also be used with pattern matching characters, such as wildcard characters. Here we will use theechocommand to see how the wildcard character is interpreted by the shell.$ echo *.fastqSRR097977.fastq SRR098026.fastqThe
*is expanded to include any file that ends with.fastq. We can see that the output ofecho *.fastqis the same as that ofls *.fastq.What would the output look like if the wildcard could not be matched? Compare the outputs of
echo *.missingandls *.missing.
Solution
Solution
$ echo *.missing*.missing$ ls *.missingls: cannot access '*.missing': No such file or directory
3.3 Command History
If you want to repeat a command that you’ve run recently, you can access previous commands using the up arrow on your keyboard to go back to the most recent command. Likewise, the down arrow takes you forward in the command history.
A few more useful shortcuts:
- Ctrl+C will cancel the command you are writing, and give you a fresh prompt.
- Ctrl+R will do a reverse-search through your command history. This is very useful.
- Ctrl+L or the
clearcommand will clear your screen.
You can also review your recent commands with the history command, by entering:
$ historyto see a numbered list of recent commands. You can reuse one of these commands directly by referring to the number of that command.
For example, if your history looked like this:
259 ls *
260 ls /usr/bin/*.sh
261 ls *R1*fastqthen you could repeat command #260 by entering:
$ !260Type ! (exclamation point) and then the number of the command from your history.
You will be glad you learned this when you need to re-run very complicated commands.
For more information on advanced usage of history, read section 9.3 of
Bash manual.
Exercise
Find the line number in your history for the command that listed all the .sh files in
/usr/bin. Rerun that command.
3.4 Examining Files
We now know how to switch directories, run commands, and look at the contents of directories, but how do we look at the contents of files?
One way to examine a file is to print out all of the
contents using the command cat.
Enter the following command from within the untrimmed_fastq directory:
$ cat SRR098026.fastqThis will print out all of the contents of the SRR098026.fastq to the screen.
Exercise
- Print out the contents of the
./MarineGenomicsData/Week2/untrimmed_fastq/SRR097977.fastqfile. What is the last line of the file?- From your home directory, and without changing directories, use one short command to print the contents of all of the files in the
./MarineGenomicsData/Week2/untrimmed_fastqdirectory.
Solution
Solution
- The last line of the file is
C:CCC::CCCCCCCC<8?6A:C28C<608'&&&,'$. 2a.cd ~2b.cat ./MarineGenomicsData/Week2/untrimmed_fastq/*
cat is a terrific command, but when the file is really big, it can
be annoying to use. The program, less, is useful for this
case. less opens the file as read only, and lets you navigate through it.
Enter the following command:
$ less SRR097977.fastqSome navigation commands in less:
| key | action |
|---|---|
| Space | to go forward |
| b | to go backward |
| g | to go to the beginning |
| G | to go to the end |
| q | to quit |
less also gives you a way of searching through files. Use the
“/” key to begin a search. Enter the word you would like
to search for and press enter. The screen will jump to the next location where
that word is found.
Shortcut: If you hit “/” then “enter,” less will repeat
the previous search. less searches from the current location and
works its way forward. Note, if you are at the end of the file and search
for the sequence “CAA,” less will not find it. You either need to go to the
beginning of the file (by typing g) and search again using / or you
can use ? to search backwards in the same way you used / previously.
For instance, let’s search forward for the sequence TTTTT in our file.
You can see that we go right to that sequence, what it looks like,
and where it is in the file. If you continue to type / and hit return, you will move
forward to the next instance of this sequence motif. If you instead type ? and hit
return, you will search backwards and move up the file to previous examples of this motif.
Exercise
What are the next three nucleotides (characters) after the first instance of ‘TTTTT?’
Remember, the man command actually uses less internally and
therefore uses the same commands, so you can search documentation
using “/” as well!
There’s another way that we can look at files, and in this case, just look at part of them. This can be particularly useful if we just want to see the beginning or end of the file, or see how it’s formatted.
The commands are head and tail and they let you look at
the beginning and end of a file, respectively.
$ head SRR098026.fastq@SRR098026.1 HWUSI-EAS1599_1:2:1:0:968 length=35
NNNNNNNNNNNNNNNNCNNNNNNNNNNNNNNNNNN
+SRR098026.1 HWUSI-EAS1599_1:2:1:0:968 length=35
!!!!!!!!!!!!!!!!#!!!!!!!!!!!!!!!!!!
@SRR098026.2 HWUSI-EAS1599_1:2:1:0:312 length=35
NNNNNNNNNNNNNNNNANNNNNNNNNNNNNNNNNN
+SRR098026.2 HWUSI-EAS1599_1:2:1:0:312 length=35
!!!!!!!!!!!!!!!!#!!!!!!!!!!!!!!!!!!
@SRR098026.3 HWUSI-EAS1599_1:2:1:0:570 length=35
NNNNNNNNNNNNNNNNANNNNNNNNNNNNNNNNNN$ tail SRR098026.fastq+SRR098026.247 HWUSI-EAS1599_1:2:1:2:1311 length=35
#!##!#################!!!!!!!######
@SRR098026.248 HWUSI-EAS1599_1:2:1:2:118 length=35
GNTGNGGTCATCATACGCGCCCNNNNNNNGGCATG
+SRR098026.248 HWUSI-EAS1599_1:2:1:2:118 length=35
B!;?!A=5922:##########!!!!!!!######
@SRR098026.249 HWUSI-EAS1599_1:2:1:2:1057 length=35
CNCTNTATGCGTACGGCAGTGANNNNNNNGGAGAT
+SRR098026.249 HWUSI-EAS1599_1:2:1:2:1057 length=35
A!@B!BBB@ABAB#########!!!!!!!######The -n option to either of these commands can be used to print the
first or last n lines of a file.
$ head -n 1 SRR098026.fastq@SRR098026.1 HWUSI-EAS1599_1:2:1:0:968 length=35$ tail -n 1 SRR098026.fastqA!@B!BBB@ABAB#########!!!!!!!######3.5 Details on the FASTQ format
Although it looks complicated (and it is), it’s easy to understand the fastq format with a little decoding. Some rules about the format include…
| Line | Description |
|---|---|
| 1 | Always begins with ‘@’ and then information about the read |
| 2 | The actual DNA sequence |
| 3 | Always begins with a ‘+’ and sometimes the same info in line 1 |
| 4 | Has a string of characters which represent the quality scores; must have same number of characters as line 2 |
We can view the first complete read in one of the files in our dataset by using head to look at
the first four lines.
$ head -n 4 SRR098026.fastq@SRR098026.1 HWUSI-EAS1599_1:2:1:0:968 length=35
NNNNNNNNNNNNNNNNCNNNNNNNNNNNNNNNNNN
+SRR098026.1 HWUSI-EAS1599_1:2:1:0:968 length=35
!!!!!!!!!!!!!!!!#!!!!!!!!!!!!!!!!!!All but one of the nucleotides in this read are unknown (N). This is a pretty bad read!
Line 4 shows the quality for each nucleotide in the read. Quality is interpreted as the probability of an incorrect base call. To make it possible to line up each individual nucleotide with its quality score, the numerical score is converted into a code where each character represents the numerical quality score for an individual nucleotide. For example, in the line above, the quality score line is:
!!!!!!!!!!!!!!!!#!!!!!!!!!!!!!!!!!!The # character and each of the ! characters represent the encoded quality for an
individual nucleotide. The numerical value assigned to each of these characters depends on the
sequencing platform that generated the reads. The sequencing machine used to generate our data
uses the standard Sanger quality PHRED score encoding, Illumina version 1.8 onwards.
Here is a link showing what those different symbols mean for quality scores: https://support.illumina.com/help/BaseSpace_OLH_009008/Content/Source/Informatics/BS/QualityScoreEncoding_swBS.htm
Each character is assigned a quality score between 0 and 42 as shown in the chart below.
Quality encoding: !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJK
| | | | |
Quality score: 0........10........20........30........40.. This quality score is logarithmically based, so a quality score of 10 reflects a base call accuracy of 90%, but a quality score of 20 reflects a base call accuracy of 99%.
Looking back at our read:
@SRR098026.1 HWUSI-EAS1599_1:2:1:0:968 length=35
NNNNNNNNNNNNNNNNCNNNNNNNNNNNNNNNNNN
+SRR098026.1 HWUSI-EAS1599_1:2:1:0:968 length=35
!!!!!!!!!!!!!!!!#!!!!!!!!!!!!!!!!!!We can now see that the quality of each of the Ns is 0 and the quality of the only
nucleotide call (C) is also very poor (# = a quality score of 2). This is indeed a very
bad read.
3.6 Creating, moving, copying, and removing
Now we can move around in the file structure, look at files, and search files. But what if we want to copy files or move them around or get rid of them? Most of the time, you can do these sorts of file manipulations without the command line, but there will be some cases (like when you’re working with a remote computer like we are for this lesson) where it will be impossible. You’ll also find that you may be working with hundreds of files and want to do similar manipulations to all of those files. In cases like this, it’s much faster to do these operations at the command line.
3.6.1 Copying Files
When working with computational data, it’s important to keep a safe copy of that data that can’t be accidentally overwritten or deleted. For this lesson, that would be our raw data is our FASTQ files. We don’t want to accidentally change the original files, so we’ll make a copy of them and change the file permissions so that we can read from, but not write to, the files.
First, let’s make a copy of one of our FASTQ files using the cp command.
Navigate to the ~/MarineGenomicsData/Week2/untrimmed_fastq directory and enter:
$ cp SRR098026.fastq SRR098026-copy.fastq
$ ls -FSRR097977.fastq* SRR098026-copy.fastq* SRR098026.fastq*We now have two copies of the SRR098026.fastq file, one of them named SRR098026-copy.fastq. We’ll move this file to a new directory
called backup where we’ll store our backup data files.
3.6.2 Creating Directories
The mkdir command is used to make a directory. Enter mkdir
followed by a space, then the directory name you want to create:
$ mkdir backup3.6.3 Moving / Renaming
We can now move our backup file to this directory. We can
move files around using the command mv:
$ mv SRR098026-copy.fastq backup
$ ls backupSRR098026-copy.fastqThe mv command is also how you rename files. Let’s rename this file to make it clear that this is a backup:
$ cd backup
$ mv SRR098026-copy.fastq SRR098026-backup.fastq
$ lsSRR098026-backup.fastq3.6.4 File Permissions
We’ve now made a backup copy of our file, but just because we have two copies, it doesn’t make us safe. We can still accidentally delete or overwrite both copies. To make sure we can’t accidentally mess up this backup file, we’re going to change the permissions on the file so that we’re only allowed to read (i.e. view) the file, not write to it (i.e. make new changes).
View the current permissions on a file using the -l (long) flag for the ls command:
$ ls -l-rwxrwxr-x 1 exouser exouser 43332 Mar 25 01:23 SRR098026-backup.fastqThe first part of the output for the -l flag gives you information about the file’s current permissions. There are ten slots in the
permissions list. The first character in this list is related to file type, not permissions, so we’ll ignore it for now. The next three
characters relate to the permissions that the file owner has, the next three relate to the permissions for group members, and the final
three characters specify what other users outside of your group can do with the file. We’re going to concentrate on the three positions
that deal with your permissions (as the file user).
Figure by Mary Brent
Here the three positions that relate to the file user/owner are rwx. The r means that you have permission to read the file, the w
indicates that you have permission to write to (i.e. make changes to) the file, and the third position is x, indicating that you have permission to carry out the ability encoded by that space (this is the space where x or executable ability is stored, we’ll
talk more about this in a later lesson).
Our goal for now is to change permissions on this file so that you no longer have w or write permissions. We can do this using the chmod (change mode) command and subtracting (-) the write permission -w.
$ chmod -w SRR098026-backup.fastq
$ ls -l -r-xr-xr-x 1 exouser exouser 43332 Mar 25 01:23 SRR098026-backup.fastqChmod can also change the permission to only the user (u), group (g), and/or other (o). Let’s add reading (r), writing (x), and execute (x) permissions to group owners (because coding is better with friends!).
$ chmod g=rwx SRR098026-backup.fastq
$ ls -l -r-xrwxr-x 1 exouser exouser 43332 Mar 25 01:23 SRR098026-backup.fastq3.6.5 Removing
To prove to ourselves that you no longer have the ability to modify this file, try deleting it with the rm command:
$ rm SRR098026-backup.fastqYou’ll be asked if you want to override your file permissions:
rm: remove write-protected regular file ‘SRR098026-backup.fastq’? You should enter n for no. If you enter n (for no), the file will not be deleted. If you enter y, you will delete the file. This gives us an extra
measure of security, as there is one more step between us and deleting our data files.
Important: The rm command permanently removes the file. Be careful with this command. It doesn’t
just nicely put the files in the Trash. They’re really gone.
By default, rm will not delete directories. You can tell rm to
delete a directory using the -r (recursive) option. Let’s delete the backup directory
we just made.
Enter the following command:
$ cd ..
$ rm -r backupThis will delete not only the directory, but all files within the directory. If you have write-protected files in the directory, you will be asked whether you want to override your permission settings (say yes here).
Exercise
Starting in the
~/MarineGenomicsData/Week2/untrimmed_fastq/directory, do the following: 1. Make sure that you have deleted your backup directory and all files it contains.
2. Create a backup of each of your FASTQ files usingcp. (Note: You’ll need to do this individually for each of the two FASTQ files. We haven’t learned yet how to do this with a wildcard.)
3. Use a wildcard to move all of your backup files to a new backup directory.
4. Change the permissions on all of your backup files to be write-protected.
Solution
Solution
rm -r backup
cp SRR098026.fastq SRR098026-backup.fastqandcp SRR097977.fastq SRR097977-backup.fastq
mkdir backupandmv *-backup.fastq backupchmod -w backup/*-backup.fastq
It’s always a good idea to check your work withls -l backup. You should see something like:-r--r--r-- 1 dcuser dcuser 47552 Nov 15 23:06 SRR097977-backup.fastq -r--r--r-- 1 dcuser dcuser 43332 Nov 15 23:06 SRR098026-backup.fastq
Now you have the ability to edit and explore your directories, and manipulate the files within them!
- Part 1 Keypoints:
- You can view file contents using
less,cat,headortail.
- You can view file contents using
- The commands
cp,mv,rm`` andmkdir` are useful for manipulating existing files and creating new directories. - You can view file permissions using
ls -land change permissions usingchmod. - The
historycommand and the up arrow on your keyboard can be used to repeat recently used commands.
3.7 Searching within, editing, and redirecting files
- Questions:
- How can I search within files?
- How can I combine existing commands to do new things?
- Objectives:
- Employ the
grepcommand to search for information within files. - Print the results of a command to a file.
- Construct command pipelines with two or more stages.
- Employ the
3.8 Searching files
In addition to less, we can also
search within files without even opening them, using grep. grep is a command-line
utility for searching plain-text files for lines matching a specific set of
characters (sometimes called a string).
Let’s give it a try!
Nucleotide abbreviations
The four nucleotides that appear in DNA are abbreviated
A,C,TandG. Unknown nucleotides are represented with the letterN. AnNappearing in a sequencing file represents a position where the sequencing machine was not able to confidently determine the nucleotide in that position. You can think of anNas being aNy nucleotide at that position in the DNA sequence.
We’ll search for strings inside of our fastq files. Let’s first make sure we are in the correct directory:
$ cd ~/MarineGenomicsData/Week2/untrimmed_fastqSuppose we want to see how many reads in our file have really bad segments containing 10 consecutive unknown nucleotides (Ns).
Determining quality
In this lesson, we’re going to be manually searching for strings of
Ns within our sequence results to illustrate some principles of file searching. It can be really useful to do this type of searching to get a feel for the quality of your sequencing results, however, in your research you will most likely use a bioinformatics tool that has a built-in program for filtering out low-quality reads. You’ll learn how to use one such tool in a later lesson.
Let’s search for the string NNNNNNNNNN in the SRR098026 file:
$ grep NNNNNNNNNN SRR098026.fastqThis command returns a lot of output to the terminal. Every single line in the SRR098026 file that contains at least 10 consecutive Ns is printed to the terminal, regardless of how long or short the file is. We may be interested not only in the actual sequence which contains this string, but in the name (or identifier) of that sequence. We discussed previously that the identifier line immediately precedes the nucleotide sequence for each read in a FASTQ file. We may also want to inspect the quality scores associated with each of these reads. To get all of this information, we will return the line immediately before each match and the two lines immediately after each match.
We can use the -B argument for grep to return a specific number of lines before
each match. The -A argument returns a specific number of lines after each matching line. Here we want the line before and the two lines after each
matching line, so we add -B1 -A2 to our grep command:
$ grep -B1 -A2 NNNNNNNNNN SRR098026.fastqOne of the sets of lines returned by this command is:
@SRR098026.177 HWUSI-EAS1599_1:2:1:1:2025 length=35
CNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
+SRR098026.177 HWUSI-EAS1599_1:2:1:1:2025 length=35
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Exercise
Search for the sequence
GNATNACCACTTCCin theSRR098026.fastqfile. Have your search return all matching lines and the name (or identifier) for each sequence that contains a match.Search for the sequence
AAGTTin both FASTQ files. Have your search return all matching lines and the name (or identifier) for each sequence that contains a match.
Solution
Solution
grep -B1 GNATNACCACTTCC SRR098026.fastq@SRR098026.245 HWUSI-EAS1599_1:2:1:2:801 length=35 GNATNACCACTTCCAGTGCTGANNNNNNNGGGATG
grep -B1 AAGTT *.fastqSRR097977.fastq-@SRR097977.11 209DTAAXX_Lenski2_1_7:8:3:247:351 length=36 SRR097977.fastq:GATTGCTTTAATGAAAAAGTCATATAAGTTGCCATG -- SRR097977.fastq-@SRR097977.67 209DTAAXX_Lenski2_1_7:8:3:544:566 length=36 SRR097977.fastq:TTGTCCACGCTTTTCTATGTAAAGTTTATTTGCTTT -- SRR097977.fastq-@SRR097977.68 209DTAAXX_Lenski2_1_7:8:3:724:110 length=36 SRR097977.fastq:TGAAGCCTGCTTTTTTATACTAAGTTTGCATTATAA -- SRR097977.fastq-@SRR097977.80 209DTAAXX_Lenski2_1_7:8:3:258:281 length=36 SRR097977.fastq:GTGGCGCTGCTGCATAAGTTGGGTTATCAGGTCGTT -- SRR097977.fastq-@SRR097977.92 209DTAAXX_Lenski2_1_7:8:3:353:318 length=36 SRR097977.fastq:GGCAAAATGGTCCTCCAGCCAGGCCAGAAGCAAGTT -- SRR097977.fastq-@SRR097977.139 209DTAAXX_Lenski2_1_7:8:3:703:655 length=36 SRR097977.fastq:TTTATTTGTAAAGTTTTGTTGAAATAAGGGTTGTAA -- SRR097977.fastq-@SRR097977.238 209DTAAXX_Lenski2_1_7:8:3:592:919 length=36 SRR097977.fastq:TTCTTACCATCCTGAAGTTTTTTCATCTTCCCTGAT -- SRR098026.fastq-@SRR098026.158 HWUSI-EAS1599_1:2:1:1:1505 length=35 SRR098026.fastq:GNNNNNNNNCAAAGTTGATCNNNNNNNNNTGTGCG
3.9 Redirecting output
grep allowed us to identify sequences in our FASTQ files that match a particular pattern.
All of these sequences were printed to our terminal screen, but in order to work with these
sequences and perform other operations on them, we will need to capture that output in some
way.
We can do this with something called “redirection.” The idea is that we are taking what would ordinarily be printed to the terminal screen and redirecting it to another location. In our case, we want to print this information to a file so that we can look at it later and use other commands to analyze this data.
The command for redirecting output to a file is >.
Let’s try out this command and copy all the records (including all four lines of each record)
in our FASTQ files that contain
‘NNNNNNNNNN’ to another file called bad_reads.fastq.
$ grep -B1 -A2 NNNNNNNNNN SRR098026.fastq > bad_reads.fastqFile extensions
In the code above, we have saved the bad reads as a FASTQ file, which may seem like the obvious file extension as it will be holding FASTQ formatted data that we’re extracting from our FASTQ files. But as we proceed with the exercises, we will be working with the exact same file, which we will now save as a
.txtfile. This will still be a FASTQ file even though it does not have a
name with a.fastqextension. We are doing this as using a.fastqextension will lead us to problems when we move to using wildcards later in this episode. We’ll point out where this becomes important. For now, it’s good that we’re thinking about file extensions!
$ grep -B1 -A2 NNNNNNNNNN SRR098026.fastq > bad_reads.txtThe prompt should sit there a little bit, and then it should look like nothing
happened. But type ls. You should see a new file called bad_reads.txt.
We can check the number of lines in our new file using a command called wc.
wc stands for word count. This command counts the number of words, lines, and characters
in a file. The FASTQ file may change over time, so given the potential for updates,
make sure your file matches your instructor’s output.
‘wc’ gives the following output:
$ wc bad_reads.txt 537 1073 23217 bad_reads.txtThis will tell us the number of lines, words and characters in the file. If we
want only the number of lines, we can use the -l flag for lines.
$ wc -l bad_reads.txt537 bad_reads.txtExercise
How many sequences are there in
SRR098026.fastq? Remember that every sequence is formed by four lines.
Solution
Solution
$ wc -l SRR098026.fastq996Now you can divide this number by four to get the number of sequences in your fastq file
Exercise
How many sequences in
SRR098026.fastqcontain at least 3 consecutive Ns?
We might want to search multiple FASTQ files for sequences that match our search pattern.
However, we need to be careful, because each time we use the > command to redirect output
to a file, the new output will replace the output that was already present in the file.
This is called “overwriting” and, just like you don’t want to overwrite your video recording
of your kid’s first birthday party, you also want to avoid overwriting your data files.
$ grep -B1 -A2 NNNNNNNNNN SRR098026.fastq > bad_reads.txt
$ wc -l bad_reads.txt537 bad_reads.txt$ grep -B1 -A2 NNNNNNNNNN SRR097977.fastq > bad_reads.txt
$ wc -l bad_reads.txt0 bad_reads.txtHere, the output of our second call to wc shows that we no longer have any lines in our bad_reads.txt file. This is
because the second file we searched (SRR097977.fastq) does not contain any lines that match our
search sequence. So our file was overwritten and is now empty.
We can avoid overwriting our files by using the command >>. >> is known as the “append redirect” and will
append new output to the end of a file, rather than overwriting it.
$ grep -B1 -A2 NNNNNNNNNN SRR098026.fastq > bad_reads.txt
$ wc -l bad_reads.txt537 bad_reads.txt$ grep -B1 -A2 NNNNNNNNNN SRR097977.fastq >> bad_reads.txt
$ wc -l bad_reads.txt537 bad_reads.txtThe output of our second call to wc shows that we have not overwritten our original data.
We can also do this with a single line of code by using a wildcard:
$ grep -B1 -A2 NNNNNNNNNN *.fastq > bad_reads.txt
$ wc -l bad_reads.txt537 bad_reads.txtFile extensions - part 2
This is where we would have trouble if we were naming our output file with a
.fastqextension. If we already had a file calledbad_reads.fastq(from our previousgreppractice) and then ran the command above using a.fastqextension instead of a.txtextension,grepwould give us a warning.grep -B1 -A2 NNNNNNNNNN *.fastq > bad_reads.fastqgrep: input file ‘bad_reads.fastq’ is also the output
grepis letting you know that the output filebad_reads.fastqis also included in yourgrepcall because it matches the*.fastqpattern. Be careful with this as it can lead to some unintended results.
Since we might have multiple different criteria we want to search for,
creating a new output file each time has the potential to clutter up our workspace. We also
thus far haven’t been interested in the actual contents of those files, only in the number of
reads that we’ve found. We created the files to store the reads and then counted the lines in
the file to see how many reads matched our criteria. There’s a way to do this, however, that
doesn’t require us to create these intermediate files - the pipe command (|).
What | does is take the output of that command and immediately uses it as an input to another command.
Maybe our goal is to just look at an output of a grep command, so instead of typing a grep command and then subsequently typing less, we can save time and effort by piping them together!
Here we redirect our output from our grep call through the less command.
$ grep -B1 -A2 NNNNNNNNNN SRR098026.fastq | lessWe can now see the output from our grep call within the less interface. We can use the up and down arrows
to scroll through the output and use q to exit less.
If we don’t want to create a file before counting lines of output from our grep search, we could directly pipe
the output of the grep search to the command wc -l. This can be helpful for investigating your output if you are not sure
you would like to save it to a file.
$ grep -B1 -A2 NNNNNNNNNN SRR098026.fastq | wc -l Because we asked grep for all four lines of each FASTQ record, we need to divide the output by
four to get the number of sequences that match our search pattern. Since 802 / 4 = 200.5 and we
are expecting an integer number of records, there is something added or missing in bad_reads.txt.
If we explore bad_reads.txt using less, we might be able to notice what is causing the uneven
number of lines. Luckily, this issue happens by the end of the file so we can also spot it with tail.
$ grep -B1 -A2 NNNNNNNNNN SRR098026.fastq > bad_reads.txt
$ tail bad_reads.txt@SRR098026.133 HWUSI-EAS1599_1:2:1:0:1978 length=35
ANNNNNNNNNTTCAGCGACTNNNNNNNNNNGTNGN
+SRR098026.133 HWUSI-EAS1599_1:2:1:0:1978 length=35
#!!!!!!!!!##########!!!!!!!!!!##!#!
--
--
@SRR098026.177 HWUSI-EAS1599_1:2:1:1:2025 length=35
CNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
+SRR098026.177 HWUSI-EAS1599_1:2:1:1:2025 length=35
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!The fifth and six lines in the output display “–” which is the default action for grep to separate groups of
lines matching the pattern, and indicate groups of lines which did not match the pattern so are not displayed.
To fix this issue, we can redirect the output of grep to a second instance of grep as follows.
$ grep -B1 -A2 NNNNNNNNNN SRR098026.fastq | grep -v '^--' > bad_reads.fastq
tail bad_reads.fastq+SRR098026.132 HWUSI-EAS1599_1:2:1:0:320 length=35
#!!!!!!!!!##########!!!!!!!!!!##!#!
@SRR098026.133 HWUSI-EAS1599_1:2:1:0:1978 length=35
ANNNNNNNNNTTCAGCGACTNNNNNNNNNNGTNGN
+SRR098026.133 HWUSI-EAS1599_1:2:1:0:1978 length=35
#!!!!!!!!!##########!!!!!!!!!!##!#!
@SRR098026.177 HWUSI-EAS1599_1:2:1:1:2025 length=35
CNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
+SRR098026.177 HWUSI-EAS1599_1:2:1:1:2025 length=35
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!The -v option in the second grep search stands for --invert-match meaning grep will now only display the
lines which do not match the searched pattern, in this case '^--'. The caret (^) is an anchoring
character matching the beginning of the line, and the pattern has to be enclose by single quotes so grep does
not interpret the pattern as an extended option (starting with –).
Redirecting output is often not intuitive, and can take some time to get used to. Once you’re comfortable with redirection, however, you’ll be able to combine any number of commands to do all sorts of exciting things with your data!
None of the command line programs we’ve been learning do anything all that impressive on their own, but when you start chaining them together, you can do some really powerful things very efficiently.
- Keypoints:
grepis a powerful search tool with many options for customization.>,>>, and|are different ways of redirecting output.command > fileredirects a command’s output to a file.command >> fileredirects a command’s output to a file without overwriting the existing contents of the file.command_1 | command_2redirects the output of the first command as input to the second command.
3.10 Writing Scripts and Working with Data
- Questions:
- How can we automate a commonly used set of commands?
- Objectives:
- Use the
nanotext editor to modify text files. - Write a basic shell script.
- Use the
bashcommand to execute a shell script. - Use
chmodto make a script an executable program.
- Use the
3.11 Writing files
We’ve been able to do a lot of work with files that already exist, but what if we want to write our own files? We’re not going to type in a FASTA file, but we’ll see as we go through other tutorials, there are a lot of reasons we’ll want to write a file, or edit an existing file.
To add text to files, we’re going to use a text editor called Nano. We’re going to create a file to take notes about what we’ve been doing with the data files.
This is good practice when working in bioinformatics. We can create a file called README.txt that describes the data files in the directory or documents how the files in that directory were generated. As the name suggests, it’s a file that we or others should read to understand the information in that directory.
Let’s change our working directory to ~/MarineGenomicsData/Week2/untrimmed_fastq using cd,
then run nano to create a file called README.txt:
$ cd ~/MarineGenomicsData/Week2/untrimmed_fastq
$ nano README.txtYou should see something like this:

The text at the bottom of the screen shows the keyboard shortcuts for performing various tasks in nano. We will talk more about how to interpret this information soon.
Which Editor?
Which Editor?
When we say, “
nanois a text editor,” we really do mean “text”: it can only work with plain character data, not tables, images, or any other human-friendly media. We use it in examples because it is one of the least complex text editors. However, because of this trait, it may not be powerful enough or flexible enough for the work you need to do after this workshop. On Unix systems (such as Linux and Mac OS X), many programmers use Emacs or Vim (both of which require more time to learn), or a graphical editor such as Gedit. On Windows, you may wish to use Notepad++. Windows also has a built-in editor callednotepadthat can be run from the command line in the same way asnanofor the purposes of this lesson.No matter what editor you use, you will need to know where it searches for and saves files. If you start it from the shell, it will (probably) use your current working directory as its default location.
Let’s type in a few lines of text. Describe what the files in this
directory are, what you’ve been doing with them, what date you created/edited them.
Once we’re happy with our text, we can press Ctrl-O (press the Ctrl or Control key and, while
holding it down, press the O key) to write our data to disk. You’ll be asked what file we want to save this to:
press Return to accept the suggested default of README.txt.
Once our file is saved, we can use Ctrl-X to quit the editor and return to the shell.
Control, Ctrl, or ^ Key
The Control key is also called the “Ctrl” key. There are various ways in which using the Control key may be described. For example, you may see an instruction to exit as pressing the Ctrl key and the X key, described as any of:
Control-XControl+XCtrl-XCtrl+X^XC-xIn
nano, along the bottom of the screen you’ll see^G Get Help ^O WriteOut. This means that you can use Ctrl-G to get help and Ctrl-O to save your file.
Now you’ve written a file! You can take a look at it with less or cat, or open it up again and edit it with nano.
Exercise
Exercise
Open
README.txtand at the bottom add a song title from your ideal ‘coding playlist’ and save the file.
Solution
Solution
Use
nano README.txtto open the file.
Add your song and then use Ctrl-X followed byyand Enter to save.
3.12 Writing scripts
A really powerful thing about the command line is that you can write scripts. Scripts let you save commands to run them and also lets you put multiple commands together. Though writing scripts may require an additional time investment initially, this can save you time as you run them repeatedly. Scripts can also address the challenge of reproducibility: if you need to repeat an analysis, you retain a record of your command history within the script.
One thing we will commonly want to do with sequencing results is pull out bad reads and write them to a file to see if we can figure out what’s going on with them. We’re going to look for reads with long sequences of N’s like we did before, but now we’re going to write a script, so we can run it each time we get new sequences, rather than type the code in by hand each time.
We’re going to create a new file to put this command in. We’ll call it bad-reads-script.sh. The sh isn’t required, but using that extension tells us that it’s a shell script.
$ nano bad-reads-script.shBad reads have a lot of N’s, so we’re going to look for NNNNNNNNNN with grep. We want the whole FASTQ record, so we’re also going to get the one line above the sequence and the two lines below. We also want to look in all the files that end with .fastq, so we’re going to use the * wildcard.
grep -B1 -A2 -h NNNNNNNNNN *.fastq | grep -v '^--' > scripted_bad_reads.txtCustom
grepcontrolWe introduced the
-voption in the previous episode, now we are using-hto “Suppress the prefixing of file names on output” according to the documentation shown byman grep.
Type your grep command into the file and save it as before. Be careful that you did not add the $ at the beginning of the line.
Now comes the neat part. We can run this script. Type:
$ bash bad-reads-script.shIt will look like nothing happened, but now if you look at scripted_bad_reads.txt, you can see that there are now reads in the file.
Making the script into a program Exercise
We had to type bash because we needed to tell the computer what program to use to run this script. Instead, we can turn this script into its own program. We need to tell it that it’s a program by making it executable. We can do this by changing the file permissions. We talked about permissions in an earlier episode.
First, let’s look at the current permissions.
$ ls -l bad-reads-script.sh-rw-rw-r-- 1 exouser exouser 75 Apr 8 12:46 bad-reads-script.shWe see that it says -rw-r--r--. This shows that the file can be read by any user and written to by the file owner (you). We want to change these permissions so that the file can be executed as a program using ./ .
We use the command chmod like we did earlier when we removed write permissions. Here we are adding (+) executable permissions (+x).
$ chmod +x bad-reads-script.shNow let’s look at the permissions again.
$ ls -l bad-reads-script.sh-rwxrwxr-x 1 exouser exouser 75 Apr 8 12:48 bad-reads-script.shNow we see that it says -rwxr-xr-x. The x’s that are there now tell us we can run it as a program. So, let’s try it! We’ll need to put ./ at the beginning so the computer knows to look here in this directory for the program.
$ ./bad-reads-script.shThe script should run the same way as before, but now we’ve created our very own computer program!
3.13 Computing magic with for loops
Loops are key to productivity improvements through automation as they allow us to execute commands repeatedly. Similar to wildcards and tab completion, using loops also reduces the amount of typing (and typing mistakes). Loops are helpful when performing operations on groups of sequencing files, such as unzipping or trimming multiple files. We will use loops for these purposes in subsequent analyses.
When the shell sees the keyword for, it knows to repeat a command (or group of commands) once for each item in a list.
Each time the loop runs (called an iteration), an item in the list is assigned in sequence to the variable, and
the commands inside the loop are executed, before moving on to the next item in the list. Inside the loop, we call for
the variable’s value by putting $ in front of it. The $ tells the shell interpreter to treat the variable
as a variable name and substitute its value in its place, rather than treat it as text or an external command. In shell programming, this is usually called “expanding” the variable.
Let’s write a for loop to show us the first two lines of the fastq files we downloaded earlier. You will notice the shell prompt changes from $ to > and back again as we were typing in our loop. The second prompt, >, is different to remind us that we haven’t finished typing a complete command yet. A semicolon, ;, can be used to separate two commands written on a single line.
$ cd ~/data_week2/Week2/data_week2/untrimmed_fastq$ for filename in *.fastq
do
head -n 2 ${filename}
doneThe for loop begins with the formula for <variable> in <group to iterate over>. In this case, the word filename is designated
as the variable to be used over each iteration. In our case each fastq file will be sequentially substituted for filename
because they fit the pattern of ending with .fastq in the directory we’ve specified. The next line of the for loop is do. The next line is
the code that we want to execute. We are telling the loop to print the first two lines of each variable we iterate over. Finally, the
word done ends the loop.
After executing the loop, you should see the first two lines of both fastq files printed to the terminal. Let’s create a loop that will save this information to a file.
$ for filename in *.fastq
do
head -n 2 ${filename} >> seq_info.txt
doneWhen writing a loop, you will not be able to return to previous lines once you have pressed Enter. Remember that we can cancel the current command using
- Ctrl+C
if you notice a mistake that is going to prevent your loop for executing correctly.
Note that we are using >> to append the text to our seq_info.txt file. If we used >, the seq_info.txt file would be rewritten
every time the loop iterates, so it would only have text from the last variable used. Instead, >> adds to the end of the file.
3.14 Using Basename in for loops
Basename is a function in UNIX that is helpful for removing a uniform part of a name from a list of files. In this case, we will use basename to remove the .fastq extension from the files that we’ve been working with.
$ basename SRR097977.fastq .fastqWe see that this returns just the SRR accession, and no longer has the .fastq file extension on it.
SRR097977If we try the same thing but use .fasta as the file extension instead, nothing happens. This is because basename only works when it exactly matches a string in the file.
$ basename SRR097977.fastq .fastaSRR097977.fastqBasename is really powerful when used in a for loop. It allows to access just the file prefix, which you can use to name things. Let’s try this.
Inside our for loop, we create a new name variable. We call the basename function inside the parenthesis, then give our variable name from the for loop, in this case ${filename}, and finally state that .fastq should be removed from the file name. It’s important to note that we’re not changing the actual files, we’re creating a new variable called name. The line > echo $name will print to the terminal the variable name each time the for loop runs. Because we are iterating over two files, we expect to see two lines of output.
$ for filename in *.fastq
do
name=$(basename ${filename} .fastq)
echo ${name}
doneExercise
Exercise
Print the file prefix of all of the
.txtfiles in our current directory.
One way this is really useful is to move files. Let’s rename all of our .txt files using mv so that they have the years on them, which will document when we created them.
$ for filename in *.txt
> do
> name=$(basename ${filename} .txt)
> mv ${filename} ${name}_2019.txt
> done