Wednesday, 22 January 2020

mv and rename Commands

I created a file called myself:
 
Red Hat > ls
Red Hat > touch myself
Red Hat > ls
myself
Red Hat >
 
I decided it should have been called yourself so I used mv to change its name:
 
Red Hat > mv myself yourself
Red Hat > ls
yourself
Red Hat >
 
Then I decided to use the rename command to call it himself instead. To do this I had to provide the part of the name I wanted to change, what I wanted to change it to and the filename to act upon (if that makes sense):
 
Red Hat > rename yourself himself yourself
Red Hat > ls
himself
Red Hat >
 
This approach is more complicated but it gives greater flexibility. To try this out I created several files with .txt suffixes:
 
Red Hat > rm *
Red Hat > touch file{1..5}.txt
Red Hat > ls
file1.txt  file2.txt  file3.txt  file4.txt  file5.txt
Red Hat >
 
I then decided to remove the suffixes and did this as follows:
 
Red Hat > rename .txt '' file*
Red Hat > ls
file1  file2  file3  file4  file5
Red Hat >

Tuesday, 21 January 2020

Octal Numbers

This is a variation on a Linux challenge I found elsewhere on the Internet. I created a file of numbers as follows:
 
Red Hat >cat file_of_numbers
134
065
258
168
Red Hat >
 
I wrote the following simple script to add the numbers, hoping that the result would be 625:
 
Red Hat >cat count_total.bash
#!/bin/bash
total=0
for x in `cat file_of_numbers`
do
((total+=$x))
done
echo "Total = $total"
Red Hat >
 
However, when I ran it the result was slightly different:
 
Red Hat >./count_total.bash
Total = 613
Red Hat >
 
That was because the leading zero in 065 told Linux to treat it as octal which equals 6x8+5 = 53 in decimal.
 
I removed the leading zero:
 
Red Hat >cat file_of_numbers
134
65
258
168
Red Hat >
 
…then Linux gave me the answer I wanted:
 
Red Hat >./count_total.bash
Total = 625
Red Hat >

Friday, 17 January 2020

How to See the OS Version in Red Hat Linux

You can see your operating system version in Red Hat Linux as follows:

Red Hat > cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.7 (Maipo)
Red Hat >

Tuesday, 14 January 2020

How to Process a File Line by Line


Sometimes you need to process a file line by line. You can do this as follows:
 
First you need a file. Here is one I made earlier:
 
Linux > cat input_file
0123456789
9876543210
ABCDEFGHIJ
KLMNOPQRST
Linux >
 
I wrote this script to process the file I had created:
 
Linux > cat script.ksh
#!/bin/bash
i=1
for j in `cat input_file`
do
echo "Line $i = $j"
((i+=1))
done
Linux >
 
It produced the following output when I ran it:
 
Linux > ./script.ksh
Line 1 = 0123456789
Line 2 = 9876543210
Line 3 = ABCDEFGHIJ
Line 4 = KLMNOPQRST
Linux >