Linux Text Formatting

LinuxBeginner
Practice Now

Introduction

Text formatting is a fundamental skill for Linux users and system administrators. The ability to present data in structured, readable formats is essential for creating reports, organizing output, and making information easier to understand.

In this lab, you will learn how to use the printf command, a powerful text formatting tool in Linux. You will explore various formatting techniques including field alignment, width specification, number formatting, and using escape sequences. These skills will help you create well-structured output for scripts, data processing, and system administration tasks.

Introduction to printf Basics

The printf command in Linux is used for formatting and printing data. Unlike the simpler echo command, printf gives you precise control over how your text appears.

In this step, you will learn the basic syntax of the printf command and create your first formatted output.

First, navigate to your project directory:

cd ~/project/text_formatting

The basic syntax of printf is:

printf "format" arguments

Where:

  • "format" is a string containing text and format specifiers
  • Format specifiers start with % and define how the arguments should be formatted
  • arguments are the values to be formatted

Let's create a simple example:

printf 'Hello, %s!\n' "World"

In this command:

  • %s is a format specifier for strings
  • "World" is the argument that replaces %s
  • \n adds a new line at the end

You should see the output:

Hello, World!

Now, try using multiple arguments:

printf 'Name: %s, Role: %s\n' "Alice" "Engineer"

Output:

Name: Alice, Role: Engineer

Let's save some formatted text to a file:

printf 'Today_s date: %s\n' "$(date +%Y-%m-%d)" > date.txt
cat date.txt

This command:

  1. Uses $(date +%Y-%m-%d) to get the current date in YYYY-MM-DD format
  2. Formats it with printf
  3. Saves the output to a file named date.txt
  4. Displays the file contents

Formatting Strings with Width and Alignment

When displaying data in columns or tables, controlling the width and alignment of text becomes important. In this step, you will learn how to specify field width and alignment for string data.

The format specifier for strings with width control follows this pattern:
%[flags][width]s

Where:

  • [width] specifies the minimum field width
  • [flags] controls alignment and other options (- for left alignment)

Let's create a file with formatted columns:

touch formatted_names.txt
printf "%-15s %-10s %s\n" "First Name" "Last Name" "Department" >> formatted_names.txt
printf "%-15s %-10s %s\n" "John" "Smith" "Engineering" >> formatted_names.txt
printf "%-15s %-10s %s\n" "Mary" "Johnson" "Marketing" >> formatted_names.txt
printf "%-15s %-10s %s\n" "Robert" "Williams" "Finance" >> formatted_names.txt
cat formatted_names.txt

In this example:

  • %-15s formats the first column as a left-aligned string with a width of 15 characters
  • %-10s formats the second column as a left-aligned string with a width of 10 characters
  • %s formats the third column as a standard string
  • \n adds a new line at the end

The output will display a neat table with aligned columns:

First Name      Last Name  Department
John            Smith      Engineering
Mary            Johnson    Marketing
Robert          Williams   Finance

To see the difference between left and right alignment, try:

printf "Left aligned:  '%-10s'\n" "text"
printf "Right aligned: '%10s'\n" "text"

Output:

Left aligned:  'text      '
Right aligned: '      text'

Formatting Numbers and Decimal Values

The printf command offers various options for formatting numbers, including integers and floating-point values. In this step, you will learn how to control the display of numeric data.

For integers, the basic format specifier is %d. Let's create a file with formatted numbers:

touch numerical_data.txt
printf "Decimal: %d, Padded: %05d\n" 42 42 > numerical_data.txt
cat numerical_data.txt

In this example:

  • %d displays the number as a simple decimal integer
  • %05d displays the number as a 5-digit decimal integer, padded with leading zeros

Output:

Decimal: 42, Padded: 00042

For floating-point numbers, you can use %f and control precision:

printf "Float: %f, Rounded: %.2f\n" 3.14159 3.14159 >> numerical_data.txt
cat numerical_data.txt

In this example:

  • %f displays the full floating-point number
  • %.2f displays the floating-point number rounded to 2 decimal places

The complete file now contains:

Decimal: 42, Padded: 00042
Float: 3.141590, Rounded: 3.14

You can also format numbers with different number systems:

printf "Decimal: %d, Hexadecimal: %x, Octal: %o\n" 16 16 16 >> numerical_data.txt
cat numerical_data.txt

Output added to file:

Decimal: 16, Hexadecimal: 10, Octal: 20

Using Escape Sequences

Escape sequences in the printf command allow you to include special characters and control codes in your formatted text. In this step, you will learn how to use various escape sequences.

Common escape sequences include:

  • \n - Newline
  • \t - Tab
  • \" - Double quote
  • \\ - Backslash
  • \b - Backspace

Let's create a file with examples of escape sequences:

touch escape_sequences.txt
printf "Lines:\nFirst line\nSecond line\n" > escape_sequences.txt
printf "Tabs:\tColumn1\tColumn2\tColumn3\n" >> escape_sequences.txt
printf "Quotes: \"quoted text\"\n" >> escape_sequences.txt
cat escape_sequences.txt

The output will show how these escape sequences work:

Lines:
First line
Second line
Tabs: Column1 Column2 Column3
Quotes: "quoted text"

The %b format specifier allows interpretation of escape sequences in arguments:

printf "%b" "Newline: \\n becomes a\nnew line\n" >> escape_sequences.txt
cat escape_sequences.txt

The %b specifier is also useful for interpreting hexadecimal escape sequences that represent ASCII or Unicode characters:

printf "ASCII: %b\n" "\x48\x65\x6c\x6c\x6f" >> escape_sequences.txt
cat escape_sequences.txt

Output:

ASCII: Hello

Creating a Formatted Report

In this final step, you will combine the techniques you have learned to create a nicely formatted report. This will demonstrate how these formatting skills can be applied in practical scenarios.

Let's create a script that generates a system information report:

touch system_report.sh
chmod +x system_report.sh

Open the script file with nano:

nano system_report.sh

Add the following content to the script:

#!/bin/bash

## Define the output file
report_file="system_report.txt"

## Clear any existing report
> $report_file

## Add formatted header
printf "=======================================\n" >> $report_file
printf "       %s        \n" "SYSTEM INFORMATION REPORT" >> $report_file
printf "       %s        \n" "Generated on: $(date)" >> $report_file
printf "=======================================\n\n" >> $report_file

## CPU Information
printf "%-15s %s\n" "CPU:" "$(grep "model name" /proc/cpuinfo | head -1 | cut -d: -f2 | sed 's/^[ \t]*//')" >> $report_file

## Memory Information
total_mem=$(free -m | grep Mem | awk '{print $2}')
used_mem=$(free -m | grep Mem | awk '{print $3}')
printf "%-15s %d MB (Used: %d MB)\n" "Memory:" $total_mem $used_mem >> $report_file

## Disk Information
disk_info=$(df -h / | tail -1)
disk_size=$(echo $disk_info | awk '{print $2}')
disk_used=$(echo $disk_info | awk '{print $3}')
disk_percent=$(echo $disk_info | awk '{print $5}')
printf "%-15s %s (Used: %s, %s)\n" "Disk Space:" $disk_size $disk_used $disk_percent >> $report_file

## System Uptime
uptime_info=$(uptime -p)
printf "%-15s %s\n" "Uptime:" "$uptime_info" >> $report_file

## Add a table of processes
printf "\n%-6s %-10s %-8s %-6s %s\n" "PID" "USER" "CPU%" "MEM%" "COMMAND" >> $report_file
printf "%-6s %-10s %-8s %-6s %s\n" "--" "----" "----" "----" "-------" >> $report_file

## Get top 5 processes by CPU usage
ps aux --sort=-%cpu | head -6 | tail -5 | while read line; do
  pid=$(echo $line | awk '{print $2}')
  user=$(echo $line | awk '{print $1}')
  cpu=$(echo $line | awk '{print $3}')
  mem=$(echo $line | awk '{print $4}')
  cmd=$(echo $line | awk '{print $11}')
  printf "%-6s %-10s %-8.1f %-6.1f %s\n" "$pid" "$user" "$cpu" "$mem" "$cmd" >> $report_file
done

echo "Report generated: $report_file"

Save and exit nano (press Ctrl+O, then Enter, and then Ctrl+X).

Run the script to generate the report:

./system_report.sh

View the generated report:

cat system_report.txt

The report combines various formatting techniques:

  • Field width and alignment for organized data presentation
  • Numeric formatting for CPU and memory values
  • Headers with centered text
  • Tabular data with aligned columns

This example demonstrates how the formatting techniques you have learned can be applied to create clear, readable output for system information reporting.

Summary

In this lab, you have learned how to use the printf command for text formatting in Linux. You practiced:

  1. Basic printf syntax and string formatting
  2. Controlling field width and alignment for clean, tabular output
  3. Formatting different types of numbers, including integers and floating-point values
  4. Using escape sequences to include special characters in your output
  5. Combining these techniques to create a practical system information report

These text formatting skills are essential for creating readable output in shell scripts, generating reports, and organizing information in the terminal. The printf command gives you precise control over how your text is displayed, making it a powerful tool for Linux users and system administrators.

As you continue your Linux journey, you will find these formatting techniques valuable for presenting data clearly and professionally in your scripts and command-line applications.