Linux “seq” Command Examples

The seq command prints a sequence of integers or real numbers, suitable for piping to other programs. The seq command can come in handy in various other commands and loops to generate sequence of numbers.

The Syntax

The general syntax of the “seq” command is:

# seq [options] specification

The examples

1. To simply print a sequence of number starting from a 1, use the below command:

# seq 4
1
2
3
4

By default, seq command starts printing the sequence of numbers from 1, if not specified otherwise.

2. You can also provide an upper and lower limit to the sequence of numbers generated by the “seq” command:

# seq 6 9
6
7
8
9

3. If we need to generate some other arithmetic progression, we can use the seq command, the syntax for which is shown here:

# seq [start] [incr] [stop]

This generates the numbers start, start + incr, start + incr + incr …, all the way up to stop. Let’s understand this with an example:

# seq 1 3 10
1
4
7
10

Here, we begin with 1 and increment it by 3 each time until we get a value less than or equal to 10. The value for start, incr, and stop can be positive or negative integers or floating-point decimal numbers as well.

4. Lets see an example of negative increment which basically prints the sequence backwards. For example:

# seq 10 -2 4
10
8
6
4

Formatting the output of “seq” command

You can format the output of seq command using various arguements of the command.

1. As you have noticed in all the commands above, the output is always a sequence of numbers separated by a newline. Well, you can change it to the way you want. Use the “-s” option of seq command as shown below:

# seq -s "|" 5
1|2|3|4|5

2. You can also format the output using the “-f” option. It uses a printf style format to print each number. You can use the coversion characters like E, e, f, G, g, and % with “-f” as shown below. The default is %g.

# seq -f '##%g##' 1 5
##1##
##2##
##3##
##4##
##5##
# seq -f %f 1 5
1.000000
2.000000
3.000000
4.000000
5.000000

3. You can also equalize the widths of all numbers by padding with zeros as necessary. This option has no effect with the -f option.

# seq -w 1 10
01
02
03
04
05
06
07
08
09
10

Using seq in Bash loops

We can also use seq with a for loop using command substitution, as shown here:

$ for i in $(seq 1 0.5 4)
do
echo "The number is $i"
done

The output:

The number is 1
The number is 1.5
The number is 2
The number is 2.5
The number is 3
The number is 3.5
The number is 4
Related Post