File related Linux bash snippets

Here are some of extremely useful Linux bash snippets I use all the time to parse experimental data from my simulations.

How to extract the top (insert number here) lines from a file
Consider a file named test-file.txt. You can extract the top 14 lines from that file using the following:

How to extract specific lines in a file using regular expressions.
Consider a file, named test-file.txt, with the following lines:

To extract the lines that have 5 elements we can type:

To extract the other lines, we can simply negate that regular expression:

How to search and replace text on a file

Where string1 is what you are searching for, string2 is what you want it to be replaced with and file.txt is the file you want to perform this operation on.

How to print a specific line number inside a file using a variable

Where $LINENBR is the number of the line you want to print.

How to append 2 files, column by column, keeping particular columns

How to transfer files across computers with ssh
The scp command copies files to a remote Linux system.

To copy files from a remote system to your local system:

How to remove a file extension

How to remove redundant lines inside a file
In the terminal type:

How to delete the last line of a file
In the terminal type:

How to count the number of lines in a file and write that number into another file
In the terminal type:

Alternatively you can also store the number of lines into a shell variable.

How to perform the same operation over several files
In a bash script type:

this will print out all filenames via an echo command, that will have the regular expression FAULTY*

How to write a loop inside a bash file

How to split a string inside a bash file

How to do input parameter error testing
The variable ${CIRCUIT} is the first command line argument (${1})

How to perform a particular operation on each line of a file

How to ensure that two files have the same number of lines

Where file1.txt and file2.txt are the filenames you wish to compare.

How to count the number of characters in file
In this particular example, the character I am counting is the 0.

How to replace characters in a file
This particular command will replace all “:” with the newline character.

How to delete all instances of a particular character from a file
This particular command will delete all “:” from the file longString.txt and it will write it on the file readableString.txt.