grep Command in Linux Standard Examples

grep command is your friend for searching mainly text. It searches a given file for lines containing a given string or words. The grep command should be one of the most used commands and you should get familiar with it. I’m doing the same.

Below are some standard grep commands:

Search for any instance of the word ‘coffee’ in a file do:

grep 'coffee' filename

To perform a case sensitive search use the -i flag:

grep -i 'coffee' filename

The above command will give you any words matching ‘Coffee’, ‘coffee’, ‘cOffEe’. You get the idea. Latin America specialty coffee is fantastic!

To find all occurences of the word ‘new york city’ in a given directory and all its subdirectories:

grep -R 'new york city' .

Using the ‘.’ (dot or period) tells Linux to search in the current location.

I hope this little tutorial gives you some inspiration to learn more about the grep command. Check the man pages in your Linux distro:

man grep

Or install cheat in Ubuntu using apt or snap

apt install cheat or snap install cheat

Cheat works great for me. It gives me a brief summary of most Linux commands and its easy to use. Just run it your terminal for example:

cheat grep

How to display time in Python

I have been using Flask to teach myself some coding and develop a web application for people with high blood pressure to track their daily blood pressure readings.

I wanted to find a way to automatically display the time when a user takes a blood pressure reading. It was quite simple.

Use strftime() to display Time and Date

The strftime() method returns a string displaying date and time using date, time or datetime object.

In your .py file you have to import time. Below are some examples to print time in different formats:

print (time.strftime("%H:%M:%S")) - Displays time in 24hr format.
print (time.strftime("%I:%M:%S")) - Displays time in 12hr format.

See more examples in the Python official documentation. Enjoy!

Grab a coffee mug from my sister website NYCmoments.nyc

Setting Up Static IP on Ubuntu Server 20.04 LTS

Ubuntu Server 20.04 LTS uses the tricky Netplan for network configuration by default. Network configuration is a bit more tricky, but still good. The default Netplan network configuration file on Ubuntu 20.04 LTS server is /etc/netplan/00-installer-config.yaml.

First, find the network interface name which you want to configure a static IP address with the following command:

$ ip a
ip a command output
ip a command output

As you can see my network interface name is eth0@if8, it will be different for you.

Now, go brew a good cup of coffee you have to make sure that the network interface is not managed by CloudInit.

For that, open the configuration file with your favorite editor /etc/cloud/cloud.cfg.d/subiquity-disable-cloudinit-networking.cfg with the following command:

$ sudo vim /etc/cloud/cloud.cfg.d/subiquity-disable-cloudinit-networking.cfg

Make sure the configuration file contains the following line:

network: {config: disabled}

Now, open the Netplan configuration file using your favorite editor (I like using vim) /etc/netplan/00-installer-config.yaml with the following command:

sudo vim /etc/netplan/00-installer-config.yaml

To assign a static IP address to the network interface (in my case, your network interface name will be different) eth0@if8, remove everything from the Netplan configuration file /etc/netplan/00-installer-config.yaml and type in the following lines.

network:
  version: 2
  ethernets:
    eth0@if8:
      addresses: [192.168.1.160/24]
      gateway4: 192.168.1.2
      nameservers:
        addresses: [192.168.1.2, 8.8.8.8]

Now, to make sure that the configuration file does not have any syntax errors, run the following command:

sudo netplan try

If everything is good you should see a message with something like “Warning: stopping systemd-networkd.service, but it can still be activated by:…..Press ENTER before the timeout to accept the new configuration”

The new network configuration should be accepted. To make changes permanent run the following command:

sudo netplan apply

Double check the IP address run again:

ip a

Enjoy! Contact me if you have questions or leave a comment on the comments section below.

If you like to learn more about Ubuntu Server you can get this book Ubuntu Unleashed 2019 Edition: Covering 18.04, 18.10, 19.04 (13th Edition).

How to optimize images for the web using GIMP

Optimizing images for the Web means reducing its file size which in turn will make it load faster on websites. Grab some specialty coffee and follow these simple instructions.

Reducing the image size with GIMP

To reduce the image size:

  1. Open image in GIMP.
  2. Click on Image in the toolbar, then select Scale Image.
  3. In the image size, change the width to 1920px (or your own width)
  4. Select Scale
  5. Select File in the toolbar. Then select Export As.
  6. Name to your file ending with a “.jpg”
  7. Select Export
  8. In dialog box that opens, change Quality to 60.
  9. Click Advanced Options.
  10. Change Subsampling to 4:2:0 (chroma quartered)
  11. Click Export

Feel free to adjust settings to meet your image quality needs.

Contact me if you have any questions.

Linux command line history tips

Many times I found myself typing history into the terminal and then copy/paste the command I was looking for. But, then I found the below tricks to help repeat that command faster and more efficiently.

Use Control+R

I found this to be the most beneficial for me. It will do a reverse search really fast! Just press enter when you see the command you need to retype.

Repeat the previous command quickly

This is useful if you know you recently typed a command. You can use the following key combinations:

  • Use the up arrow to view the previous command and press enter to execute it.
  • Type !! and press enter from the command line
  • Type !-1 and press enter from the command line.
  • Press Control+P will display the previous command, press enter to execute it

Execute a specific command from history

For example, you can display history as usual:

history | more
1  service apache2 restart
2  ifconfig
3  ls
4  cat /etc/hosts

If you want to repeat command #2, you will type !2 as show below:

# !2
eth0      Link encap:Ethernet  HWaddr 12:38:33:b7:99:96  
          inet addr:10.0.0.17  Bcast:10.0.0.255  Mask:255.255.255.0
          inet6 addr: fe80::1038:33ff:feb7:9996/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:9001  Metric:1
          RX packets:586486972 errors:0 dropped:0 overruns:0 frame:0
          TX packets:539727562 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:363967988525 (363.9 GB)  TX bytes:491630839370 (491.6 GB)

MySQL how to insert a row into a table

Inserting data into MySQL tables is easy, but I tend to forget little details once in a while. I was having the best espresso coffee and trying to remember this one. Below is how you insert a new row into a MySQL table.

Assume you created the following table:

CREATE TABLE IF NOT EXISTS mytable (
    mytable_id INT AUTO_INCREMENT,
    title VARCHAR(255) NOT NULL,
    start_date DATE,
    due_date DATE,
    priority TINYINT NOT NULL DEFAULT 3,
    description TEXT,
    PRIMARY KEY (task_id)
);

And then you want to insert a new row into this MySQL table. Run the command below:

INSERT INTO tasks(title,priority)
VALUES('Learn MySQL INSERT Statement',1);

You should get the below from MySQL:

1 row(s) affected

That’s all! Contact me if you need help. Write in the comments section if you have questions.

How to restart a service running in docker compose

I’m playing with docker-compose for a test Flask app. My docker-compose.yml looks like this:

version: '2'
services:
  www:
    build: www/.
    ports:
      - "5000:5000"
    volumes:
      - ./www:/opt/www
    links:
      - db
    depends_on:
      - db
  db:
    build: db/.
    volumes:
      - ./database:/var/lib/mysql
    environment:
       MYSQL_ROOT_PASSWORD: supersecure

I noticed any change I made in my files within my templates folder did not take effect when I reloaded the browser locally at localhost:5000

So, I found that I can just restart the ‘www’ service defined on my docker-compose.yml file using this simple command:

docker-compose restart www

I’m not sure if this is the recommended way, but its working for now. If you have any suggestions please leave them on the comments area below.

Connect to a remote MySQL database using Linux terminal

This is simple. After you setup a user with proper access rights run the below commands.

# mysql -u yourUser -p -h <yourHostname or IP>

A little explanation:

-u tells mysql what your username

-p tells mysql you have a password and will prompt you to enter it after you press enter

-h tells mysql the hostname or IP address of your MySQL server

Good luck! Contact me if you have any questions.

Restart sound service in Ubuntu

The other day my sound stopped working on Ubuntu 18.04 desktop. I have no clue why. The sound stopped working overnight for some reason. After some research and taking a walk around Brooklyn, I found the below command to restart the sound service on Ubuntu:

pulseaudio -k && sudo alsa force-reload

All works now! Give it a try and let me know if it works for you. Follow me on Twitter @itprohelper and also check out my coffee mugs and T-Shirts shop where I design cool stuff.

Minicom error “Device /dev/ttyS0 is locked”

Sometimes if the connection to a device via Minicom is lost, the next time you start Minicom you could see an error:

Device /dev/ttyS0 is locked.

The name /dev/ttyS0 may be different, depending on your COM port. To avoid this issue you should always shut down Minicom using CTRL+A keys and then the Q key.

To resolve the issue you can kill the process as a root user. First I needed a great cup of Latin America coffee. Use the following command in your terminal:

killall -9 minicom

In Ubuntu is similar. Run the command in your terminal using sudo:

sudo killall -9 minicom

You can also try to delete the file:

LCK..ttyS0 in the /var/lock directory.

That was all for me! Hope this little tutorial was useful. If you like to learn more about networking check out this book CompTIA Network+ Certification All-in-One Exam Guide, Seventh Edition (Exam N10-007)