Bash: File content tricks

Using bash to get some data from the files can be very useful. Here are some essential tricks to get you started.

  1. See if the file has a word called “hello”:

cat file.txt |grep hello

  1. Compare two files using cmp / cmp is usually part of the diffutils package.

This part is best done with simple script. However, scripting is not mandatory when using cmp.

#!/bin/bash

# Creating two new files with: echo "Helllo" > file.txt && echo "Hello" > file2.txt

file1="file.txt"
file2="file2.txt"

if cmp "$file1" "$file2"; then
echo "Files are the same."
else
echo "Files are not the same."
fi

# Saving this script as: test.sh and making it executable with: chmod +x test.sh

This example will produce two files that are not identical. The reason is: The two files are not exact copies of each other. This is due to files being created at a different time. If we would have done:

echo "Helllo" > file.txt && cp file.txt file2.txt

then we would have created two files that are exact copies of each other.(the if loop would have ran.)

  1. Comparing two files with diff:

This example compares two files with diff. If there is nothing printed then the files have the same content.

diff file.txt file2.txt

If there is a difference between the files then the print will be something like this:

1c1

< Helllo

Helllo123

  1. Getting sha256 sums from the files:

#!/bin/bash

file1=$(sha256sum file.txt)
file2=$(sha256sum file2.txt)
echo $file1
echo $file2

Running the above script will give something like this when the files are not copies of each other:

f95e25387417bb9f1f2bec774d421729288a05da018e40e1974561802bdb61f0 file.txt
32c52ca0b2c632ce2eae820bd41d94d9e178767cbd54f108e241248a0196e570 file2.txt

  1. Seeing if the file does not exists/exists and doing something based on the result. In this case, we just echo out the result.

#!/bin/bash

file=file.txt

if [ ! -f $file ]; then
echo "$file does not exist."
elif [ -f $file ]; then
echo "$file exists."
fi

  1. Taking filename as a first argument == Avoiding hard-coded filename.

#!/bin/bash

file=$1

if [ ! -f $file ]; then
echo "$file does not exist."
elif [ -f $file ]; then
echo "$file exists."
fi

Now if I would run this command on terminal: bash test.sh file.txt

file.txt would take the place of file=$1. $1 means the first argument passed on to the command line. If I would use $2 that would mean the second argument passed on to the command line.