Category Archives: Linux

Discover DevOps roles and learn Linux from basics to advanced at DevOpsRoles.com. Detailed guides and in-depth articles to master Linux for DevOps careers.

nl command in Linux with example

Introduction

In this tutorial, we will explore how to use the nl command in Linux to number lines of files. The nl command is a powerful tool for adding line numbers to the contents of a file or standard input. This can be incredibly useful for referencing specific lines more easily or for organizing and presenting content more clearly. Let’s delve into practical examples to demonstrate how the nl command can be effectively utilized in various scenarios.

What does the nl command mean?

The nl command stands for “number lines,” and it is used in Linux to add line numbers to the contents of files or standard input. This functionality is particularly useful for referencing specific lines more easily in scripts or documents.

nl command syntax

nl [OPTION]… [FILE]…

Some common options for the “nl” command include:

  • -b <type>: Specifies the numbering style. The <type> can be a (all lines), t (non-empty lines), or n (no lines).
  • -i <increment>: Sets the line number increment. The <increment> can be any positive integer.
  • -v <number>: Sets the starting line number. The <number> can be any positive integer.
  • -w <width>: Specifies the field width for line numbers.

On the man page, the describes it

  • nl – number lines of files.
  • man nl – More details information about nl command.

nl command in Linux with an example

I have created a file nl_command.txt as below

[vagrant@DevopsRoles ~]$ cat nl_command.txt                                    
 HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.
 Devops Roles.
 Devops Roles.
 Devops Roles.
 Devops Roles.
 Hello world :)

By default, the nl command doesn’t number empty lines

[vagrant@DevopsRoles ~]$ nl nl_command.txt 
      1  HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.
      2  Devops Roles.
      3  Devops Roles.
      4  Devops Roles.
      5  Devops Roles.
      6  Hello world :)

How to number empty lines.

[vagrant@DevopsRoles ~]$ nl -b a nl_command.txt                                
      1  HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.
      2  Devops Roles.
      3  Devops Roles.
      4  Devops Roles.
      5  Devops Roles.
      6  
      7  Hello world :)

How to numbering formats

[vagrant@DevopsRoles ~]$ nl -n ln nl_command.txt                               
 1       HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.
 2       Devops Roles.
 3       Devops Roles.
 4       Devops Roles.
 5       Devops Roles.
 6       Hello world :)
 [vagrant@DevopsRoles ~]$ nl -n rz nl_command.txt 
 000001  HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.
 000002  Devops Roles.
 000003  Devops Roles.
 000004  Devops Roles.
 000005  Devops Roles.
 000006  Hello world :)

Customized numbering separator

[vagrant@DevopsRoles ~]$ nl nl_command.txt                                     
      1  HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.
      2  Devops Roles.
      3  Devops Roles.
      4  Devops Roles.
      5  Devops Roles.
      6  Hello world :)
 [vagrant@DevopsRoles ~]$ nl -s : nl_command.txt 
      1:HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.
      2:Devops Roles.
      3:Devops Roles.
      4:Devops Roles.
      5:Devops Roles.
      6:Hello world :)

Conclusion

nl command is a simple command in Linux. It uses the number of lines of files. You can refer to the manual page for the “nl” command by typing man nl in the terminal for more information and additional options available on your specific Linux distribution. Thank you for reading the DevopsRoles page!

How to Use the tr Command in Linux: Examples Included

Introduction

In this tutorial, we will explore the tr command in Linux, a versatile utility in Linux for translating or deleting characters in text. The tr command is primarily used for character-level transformations, making it an essential tool for modifying the contents of text files or input streams. By specifying certain rules, tr allows you to replace or remove specific characters efficiently. Let’s dive into practical examples to see the using tr command in Linux.

What is the purpose of the tr command?

The tr command, short for “translate,” is a powerful utility in Linux used to translate or delete characters in text data. It performs specific transformations on the contents of a file or data from a standard input, based on rules defined by the user.

tr command syntax

tr [OPTION]... [INPUT [OUTPUT]]

According to the man page, it is described as follows.

  • tr – translate or delete characters.
  • man tr – More details information about tr command.

tr command in Linux with an example

I have created a file tr_command.txt as below

[vagrant@DevopsRoles ~]$ cat tr_command.txt 
 HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.
 Devops Roles.
 Devops Roles.
 Devops Roles.
 Devops Roles.
 Hello world :)

How to convert small letters into capital letters.

[vagrant@DevopsRoles ~]$ cat tr_command.txt | tr [:lower:] [:upper:]           
 HUUPV, MY WEBSITE DEVOPSROLES.COM AND HUUPHAN.COM.SN:199X.
 DEVOPS ROLES.
 DEVOPS ROLES.
 DEVOPS ROLES.
 DEVOPS ROLES.
 HELLO WORLD :)

The following command is used to convert each space of the text by a newline (\n)

[vagrant@DevopsRoles ~]$ cat tr_command.txt | tr [:space:] '\n'                                                                                                            
 HuuPV,
 My
 website
 DevopsRoles.com
 and
 HuuPhan.com.SN:199x.
 Devops
 Roles.
 Devops
 Roles.
 Devops
 Roles.
 Devops
 Roles.
 Hello
 world
 :)

uses –s option for searching and replacing any string from a text

[vagrant@DevopsRoles ~]$ cat tr_command.txt |  tr -s ' ' '\t'
 HuuPV,  My      website DevopsRoles.com and     HuuPhan.com.SN:199x.
 Devops  Roles.
 Devops  Roles.
 Devops  Roles.
 Devops  Roles.
 Hello   world   :)

Delete numbers

[vagrant@DevopsRoles ~]$ cat tr_command.txt | tr -d "[:digit:]"
 HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:x.
 Devops Roles.
 Devops Roles.
 Devops Roles.
 Devops Roles.
 Hello world :)

Output the converted output to a file

[vagrant@DevopsRoles ~]$ cat tr_command.txt | tr "[:upper:]" "[:lower:]" > result_tr.txt 

Conclusion

The tr command is a straightforward yet powerful tool in Linux, used to translate or delete characters in text. For more detailed information and to explore additional options that may vary by Linux distribution, you can consult the manual page for the tr command by typing man tr in the terminal. Thank you for visiting the DevopsRoles page!

uniq command in Linux: A Guide to Eliminating Duplicate Lines

Introduction

In this guide, I demonstrate how to use the uniq command in Linux to handle repeated lines. We’ll explore practical examples of the uniq command in action.

What does the “uniq” command mean?

uniq” – This command is used to report or omit repeated lines.

uniq command the syntax

uniq [OPTION]... [INPUT [OUTPUT]]

In the man page, the describes it

  • uniq – report or omit repeated lines.
  • man uniq – More details information about uniq command.

How to Use Uniq Command in Linux

I have created a file uniq_command.txt as below

[vagrant@DevopsRoles ~]$ cat uniq_command.txt 
 HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.
 Devops Roles.
 Devops Roles.
 Devops Roles.
 Devops Roles.
 Hello world :)

Remove duplicate lines with the uniq command.

[vagrant@DevopsRoles ~]$ uniq uniq_command.txt 
 HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.
 Devops Roles.
 Hello world :)

The number of times a line was repeated

[vagrant@DevopsRoles ~]$ uniq -c uniq_command.txt 
       1 HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.
       4 Devops Roles.
       1 
       1 Hello world :)

It only prints the repeated lines.

[vagrant@DevopsRoles ~]$ uniq -d uniq_command.txt 
 Devops Roles.

Prints all repeated duplicate line

[vagrant@DevopsRoles ~]$ uniq -D uniq_command.txt 
 Devops Roles.
 Devops Roles.
 Devops Roles.
 Devops Roles.

How to not print the duplicate lines. Only the unique lines.

[vagrant@DevopsRoles ~]$ uniq -u uniq_command.txt 
 HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.
 Hello world :)

Conclusion

The uniq command is a straightforward tool in Linux, essential for managing and eliminating duplicate lines in files. It offers a simple yet effective way to clean data by reporting or omitting repeated entries. Thank you for visiting the DevopsRoles page and exploring this utility with us!

cut command in Linux with example

Introduction

In this tutorial, I am using the cut command in Linux to remove sections from each line of files.

The cut the command is used to extract specific sections (columns) from lines of input text or files in Linux and Unix systems. It is particularly useful for working with delimited data.

What does cut command mean?

cut – remove sections from each line of files

Syntax

cut OPTION... [FILE]...

On the man page, the description it

  • cut – remove sections from each line of files.
  • man cut – More details information about the cut command.

cut command in Linux with an example

I have created a file cut_command.txt as below

[vagrant@DevopsRoles ~]$ cat cut_command.txt 
 HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.
 Devops Roles.
 Hello world. xxx.

For delimiter-separated fields. The default delimiter is the tab character.

[vagrant@DevopsRoles ~]$ cut -d "," -f 1 cut_command.txt 
 HuuPV
 Devops Roles.
 Hello world. xxx

Get a list of all users in the Linux

[vagrant@DevopsRoles ~]$ cat /etc/passwd | cut -d ':' -f1                                                                                                                                                                              
 root
 bin
 daemon
 adm
 lp
 sync
 shutdown
 halt
 mail
 uucp
 operator
 games
 gopher
 ftp
 nobody
 vcsa
 rpc
 rpcuser
 nfsnobody
 sshd
 exim
 centos
 huupv
 gluster
 grafana
 influxdb
 mysql
 acc1
 netdata
 telegraf
 nginx
 dbus
 haldaemon

cut and sort sort

[vagrant@DevopsRoles ~]$ cat /etc/passwd | grep home | cut -d: -f1,6 | sort
 acc1:/home/acc1
 huupv:/home/huupv

You can also display the table with column -t

[vagrant@DevopsRoles ~]$ cat /etc/passwd | grep home | cut -d: -f1,6 | sort | tr ":" " "  | column -t
 acc1      /home/acc1                                                           
 huupv    /home/huupv

Extract a range of fields

cut -f 2-4 file.txt

Print a specific delimiter

cut -d ',' -f 2 --output-delimiter=" | " file.csv

Read input from a pipe

echo "data1,data2,data3" | cut -d ',' -f 2

Conclusion

cut command in Linux is a simple command in Linux. It is used to remove sections from each line of files.

These are just a few examples of how you can use the cut command. It offers various options and functionalities for extracting specific sections from text or files. You can refer to the cut man page (man cut) for more details and additional options.

Thank you for reading the DevopsRoles page!

fmt command in Linux: A Practical Guide

Introduction

In this tutorial, we’ll explore how to use the fmt command in Linux to neatly format text in files, set optimal column widths, and standardize spacing. This guide aims to enhance your text processing skills on Linux using practical examples of the fmt command. Let’s dive into the capabilities of the fmt command in Linux.

What does the fmt command mean?

fmt – a straightforward command used as an optimal text formatter.

Syntax

fmt [-WIDTH] [OPTION]... [FILE]...


In the manual page, the fmt command is described as a simple and optimal text formatting Linux. For more detailed information about the fmt command, you can refer to the man fmt section in the manual.

fmt command in Linux with an example

By default, fmt sets the column width at 75.

I have created a file fmt_command.txt

[vagrant@DevopsRoles ~]$ cat fmt_command.txt 
 HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.
 Devops Roles.
 Hello world. xxx.

fmt with no options

[vagrant@DevopsRoles ~]$ fmt fmt_command.txt 
HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.  Devops Roles.

Hello world. xxx.

How to change the width of formatting.

[vagrant@DevopsRoles ~]$ fmt --width 20 fmt_command.txt 
 HuuPV, My website
 DevopsRoles.com and
 HuuPhan.com.SN:199x.
 Devops Roles.
 Hello world. xxx.

with -u option uses one space between words and two spaces after sentences for formatting.

[vagrant@DevopsRoles ~]$ fmt -u fmt_command.txt 
 HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x.  Devops Roles.
 Hello world. xxx.

Formatting Multiple Files

You can also format multiple files simultaneously. Simply list the files as arguments:

fmt file1.txt file2.txt file3.txt

fmt will process each file and output the formatted text for all of them.

Splitting Long Lines

If you need to split long lines without breaking words, use the -s or --split-only option:

fmt -s myfile.txt

This option splits lines at spaces, ensuring words are not cut off.

Advanced Formatting Options

The fmt command offers several advanced options for more precise text formatting:

  • -c or --crown-margin: Preserve the indentation of the first two lines.
  • -t or --tagged-paragraph: Format the text as tagged paragraphs, maintaining a hanging indentation.
  • -g or --goal: Set the goal width for formatting. This is the preferred width, while the -w option sets the maximum width.

Frequently Asked Questions

What is the default width for the fmt command?

The default width is 75 characters. You can change it using the -w or --width option.

Can fmt handle multiple files at once?

Yes, you can list multiple files as arguments and fmt will format each of them.

How can I preserve indentation with fmt?

Use the -u or --uniform-spacing option to keep the original indentation intact.

What is the difference between the -w and -g options?

The -w option sets the maximum line width, while the -g option sets the goal width, which is the preferred width for formatting.

Can fmt split long lines without breaking words?

Yes, use the -s or --split-only option to split lines at spaces without cutting off words.

Conclusion

The fmt command is a straightforward Linux utility that helps format text files, set column width commands, and ensure uniform spacing. It simplifies text editing tasks, making it a valuable tool for developers and system administrators alike. Thank you for reading this guide on the DevopsRoles page!

By understanding and utilizing the various options and features of fmt, you can efficiently format text files to meet your specific requirements. Experiment with the examples provided in this guide and explore the full potential of the fmt command in your Linux environment.

chown Invalid argument centos solved problem

Good morning, I am working and changing the ownership folder of my home, but I cannot run chown command. It is Error “Invalid argument”. This is indeed an NFS4 issue. The error chown Invalid argument as following below:

[root@Client ~]# chown -R huupv:huupv /home/huupv                                                    
chown: changing ownership of `huupv/.bashrc': Invalid argument
chown: changing ownership of `huupv': Invalid argument

My environment

Client <---> NFS server

How can I fix the chown Invalid argument this

You need to check step by step as below:

NFS client:

[root@Client ~]# cat /etc/redhat-release
Centos 6

NFS Server

[root@DevopsRoles ~]# cat /etc/redhat-release
Centos 7

Configure NFS server

[root@DevopsRoles ~]# cat /etc/exports

The Content in file exports

#Data Volume Share
/mnt/data 192.168.1.12(rw,sync,no_root_squash,no_subtree_check)

Solve Problem

From the Client, we will umount and mount as below

[root@Client ~]# umount /mnt/data # if umount is busy then you need run umount -lf /mnt/data
[root@Client ~]# mount -t nfs -o vers=3 192.168.1.13:/mnt/data  /mnt/data
[root@Client ~]# chown -R huupv:huupv /home/huupv

You have solved the problem “chown Invalid argument centos” Thank you for reading the DevopsRoles page!

Spring Boot application as a service in Linux

In this tutorial, How to run Spring Boot Application as a service in Linux. Spring boot preferred deployment method via an executable jar file that contains tomcat inside.

Spring Boot application as a service

Spring Boot and Systemd

Create new file “/etc/systemd/system/myapp.service” as a service to start on reboot.

[Unit]
Description=myapp
After=syslog.target
[Service]
User=myapp
ExecStart=/var/myapp/myapp.jar
SuccessExitStatus=143
Restart=always
RestartSec=30
[Install]
WantedBy=multi-user.target

Note: You change the Description, User, and ExecStart fields suitable for your application.

Start the service:

$ sudo systemctl start myapp

Check the status is active

$ sudo systemctl status myapp

Spring Boot and System V

Create a specific user to run the service and executable JAR file.

$ cd /opt/myapp
$ sudo useradd huupv
$ sudo passwd huupv
$ sudo chown huupv:huupv myapp.jar
$ sudo chmod 500 myapp.jar

Assuming you have a Spring Boot application installed in the folder /opt/myapp . you need to create a symlink as follows:

$ sudo ln -s /opt/myapp/myapp.jar /etc/init.d/myapp

Start the service

$ sudo service myapp start

You have created the “Spring Boot application as a service in Linux“.Thank you for reading the DevopsRoles page!

Install Gradle on CentOS

In this tutorial, How to install Gradle on CentOS. Gradle is a free and Open Source that helps your build, automate and deliver better software, faster.

Prerequisites

  • Server instance : CentOS 7
  • A sudo user.

Your System update

Login into the sudo user and run the following commands to update your system.

$ sudo yum -y install epel-release
$ sudo yum -y update
$ sudo reboot

Install JDK

Gradle requires Java Development Kit (JDK) 7 or higher in order to work. Link here

Download Gradle

In this guide, I use the “binary-only” archive. Link the Gradle release page to the latest version of Gradle. Using wget command to download Gradle.

$ cd /opt/
$ wget https://downloads.gradle-dn.com/distributions/gradle-5.6.2-bin.zip

Install Gradle on CentOS

Your run the command following.

$ sudo mkdir /opt/gradle
$ sudo unzip -d /opt/gradle gradle-5.6.2-bin.zip

Set the PATH environment for Gradle executable.

$ export PATH=$PATH:/opt/gradle/gradle-5.6.2/bin

To check if the Gradle install was successful.

$ gradle -v

Your system is now built the program with Gradle. Thank you for reading the DevopsRoles page!

Redis Install and Configure: Your Database and Cache System

Introduction

This tutorial is a Step-by-Step Guide to Redis Install and Configure. Now, let’s go Redis Install and Configure.

Dive into the efficient world of Redis with this detailed guide on installation and configuration on Linux systems. Whether you’re setting up Redis for the first time or optimizing an existing installation, this tutorial offers clear, step-by-step instructions to get Redis up and running smoothly on your server.

Redis

  • It is an Open Source.
  • In-memory data structure store.
  • Used as Database.
  • Cache and message broker.
  • Redis is a key-value pair cache and store

Redis is perfect for storing sessions. All operations are performed in memory, so reading and writing will be fast

Redis Install and Configure

Download Redis

Link latest Redis home here

$ cd /opt
$ wget http://download.redis.io/releases/redis-5.0.5.tar.gz
$ sudo tar zxvf redis-5.0.5.tar.gz
$ cd redis-5.0.5

Install Redis

$ sudo make test
$ sudo make
$ sudo make install

If the following error is in make test command as below.

You need tcl 8.5 or newer in order to run the Redis test
make[1]: *** [test] Error 1
make[1]: Leaving directory `/opt/redis-5.0.5/src'
make: *** [test] Error 2

You need to install tcl

$ sudo yum install -y tcl

Again install Redis

$ sudo make test

Error

Executing test client: couldn’t execute “src/redis-benchmark”: no such file or directory.

Then perform the following steps

$ sudo make distclean
$ sudo make
$ sudo make install

Configure Redis

$ sudo mkdir /etc/redis
$ sudo cp redis.conf /etc/redis/6379.conf
$ sudo vi /etc/redis/6379.conf

The information content 6379.conf file

$ cat /etc/redis/6379.conf | grep -v "#" | sed /^$/d
 bind 127.0.0.1
 protected-mode yes
 port 6379
 tcp-backlog 511
 timeout 0
 tcp-keepalive 300
 daemonize yes
 supervised no
 pidfile /var/run/redis_6379.pid
 loglevel notice
 logfile "/var/log/redis_6379.log"
 databases 16
 always-show-logo yes
 save 900 1
 save 300 10
 save 60 10000
 stop-writes-on-bgsave-error yes
 rdbcompression yes
 rdbchecksum yes
 dbfilename dump.rdb
 dir /etc/redis/
 replica-serve-stale-data yes
 replica-read-only yes
 repl-diskless-sync no
 repl-diskless-sync-delay 5
 repl-disable-tcp-nodelay no
 replica-priority 100
 maxmemory 10240000
 lazyfree-lazy-eviction no
 lazyfree-lazy-expire no
 lazyfree-lazy-server-del no
 replica-lazy-flush no
 appendonly no
 appendfilename "appendonly.aof"
 appendfsync everysec
 no-appendfsync-on-rewrite no
 auto-aof-rewrite-percentage 100
 auto-aof-rewrite-min-size 64mb
 aof-load-truncated yes
 aof-use-rdb-preamble yes
 lua-time-limit 5000
 slowlog-log-slower-than 10000
 slowlog-max-len 128
 latency-monitor-threshold 0
 notify-keyspace-events ""
 hash-max-ziplist-entries 512
 hash-max-ziplist-value 64
 list-max-ziplist-size -2
 list-compress-depth 0
 set-max-intset-entries 512
 zset-max-ziplist-entries 128
 zset-max-ziplist-value 64
 hll-sparse-max-bytes 3000
 stream-node-max-bytes 4096
 stream-node-max-entries 100
 activerehashing yes
 client-output-buffer-limit normal 0 0 0
 client-output-buffer-limit replica 256mb 64mb 60
 client-output-buffer-limit pubsub 32mb 8mb 60
 hz 10
 dynamic-hz yes
 aof-rewrite-incremental-fsync yes
 rdb-save-incremental-fsync yes

Create Deamon for Redis

$ sudo cp utils/redis_init_script /etc/init.d/redis
$ sudo chkconfig --add redis
$ sudo chkconfig redis on
$ sudo /etc/init.d/redis start

The Redis server has been installed on your system.

$ sudo netstat -nplt | grep 6379                                            
 tcp        0      0 127.0.0.1:6379              0.0.0.0:*                   LISTEN      11567/redis-server

For more advanced details the “redis.conf” file configuration item is described as follows:

When the client is idle for a long time, close the connection

timeout 300

Specify the logging level. Redis supports four levels: debug, verbose, notice, and warning. The default is verbose.

loglevel verbose

Set the number of databases, the default database is 0, you can use the “select DBID from v$database;” command to specify the database ID on the connection

databases 16

Set the IP address and port of the master service when the machine is slav service. When Redis starts, it will automatically synchronize data from the master.

slaveof <masterip> <masterport>

When the master service is password protected, the slav service connects to the master password.

masterauth <master-password>

Set the Redis connection password. If the connection password is configured, the client needs to provide the password through the AUTH command when connecting to Redis. The default is off.

requirepass abc

Set the maximum number of client connections at the same time. The default is unlimited.

maxclients 128

Specify the maximum memory limit of Redis. Redis will load the data into the memory at startup. After the maximum memory is reached, Redis will first try to clear the expired or expired Key. When this method is processed, the maximum memory setting is still reached. The write operation will no longer be possible, but the read operation will still be possible. Redis’ new VM mechanism will store the Key in memory and the value will be stored in the swap area.

maxmemory <bytes>

You can use the same configuration file between multiple Redis instances on the same host, and each instance has its own specific configuration file.

include /path/to/local.conf

Conclusion

Successfully installing and configuring Redis enhances your application’s performance by providing rapid data access. This guide aims to equip you with the knowledge to seamlessly integrate Redis into your system, ensuring optimal setup for a robust data management solution. Thank you for reading the DevopsRoles page!

sed command in Linux with Examples

The sed command is a stream editor for filtering and transforming text. In this tutorial, How to sed command in Linux with Examples.

The sed command-Line in Linux, which stands for “stream editor,” is a powerful text processing tool used for performing various text manipulations and transformations. It reads input line by line, applies specified operations, and outputs the result. Here are a few examples of how to use the sed command line:

Syntax

sed [OPTION]... {script-only-if-no-other-script} [input-file]...

On the man page, the describes it

  • sed – modifies lines from the specified File parameter according to an edit script and writes them to standard output.
  • man sed – More details information about the sed command.

The sed command in Linux with Examples

For example, the file sed_test.txt as below

[huupv@DevopsRoles vagrant]$ cat sed_test.txt                                                                                                                                  
# /etc/ntp.conf, configuration for ntpd; see ntp.conf(5) for help

driftfile /var/lib/ntp/ntp.drift

# Enable this if you want statistics to be logged.
#statsdir /var/log/ntpstats/

statistics loopstats peerstats clockstats
filegen loopstats file loopstats type day enable
filegen peerstats file peerstats type day enable
filegen clockstats file clockstats type day enable

# Specify one or more NTP servers.

# Use servers from the NTP Pool Project. Approved by Ubuntu Technical Board
# on 2011-02-08 (LP: #104525). See http://www.pool.ntp.org/join.html for
# more information.
pool 0.ubuntu.pool.ntp.org iburst
pool 1.ubuntu.pool.ntp.org iburst
pool 2.ubuntu.pool.ntp.org iburst
pool 3.ubuntu.pool.ntp.org iburst

Append line

$ sed '/^pool 3/ a server ntp.devopsroes.com' sed_test.txt

Insert line

It will be added lines before the matching line.

$ sed '/^pool 3/i server ntp.devopsroles.com' sed_test.txt

Delete line

used d to delete matching lines. \s is escaped for regular expressions.

$ sed ' /^pool\s[0-9]\.ubuntu/d' sed_test.txt

How to write multi-line

There are two ways, use {} or other files.

Use {}

$ sed ' {
 /^pool 0/i server ntp.devopsroles.com
 /^pool\s[0-9]/d
 } ' ./sed_test.txt

create a ntp.sed file and read with the -f option.

The content ntp.sed file.

/^$/d
/^\s*#/d
/^pool 0/ i server ntp.devopsroles.com prefer
/^pool\s[0-9]\.ubuntu/d

Explain the above line.

/^$/d - Delete blank lines.
/^\s*#/d - Delete the line following # after any space including 0 (Delete comment line of #)

As a result

$ sed -f ntp.sed sed_test.txt

The backup file before changing the original file has been modified.

$ sed -i.bak -f ntp.sed ntp.conf

Print specific lines from a file

sed -n '2,5p' input_file

Delete lines matching a pattern

sed '/pattern/d' input_file

Append text after a specific line

sed '/pattern/a\new_line' input_file

Conclusion

sed Linux is a simple command in Linux. It uses the number of lines of files. These are just a few examples of how to use the sed command in Linux.

The sed command offers a wide range of text manipulation capabilities, including search and replace, insertions, deletions, and more. Thank you for reading the DevopsRoles page!