print_lines.sh
Условие задания (русский)
Напишите Bash-скрипт print_lines.sh, который обрабатывает все строки заданного текстового файла и выводит только выбранные строки.
- Имя текстового файла передаётся как первый аргумент скрипта.
- Второй аргумент является необязательным и трактуется как положительное целое число
n. - Если второй аргумент не задан, используйте значение по умолчанию
n = 1. - Скрипт должен выводить каждую n-ю строку файла.
Пример содержимого файла
LINE 1
LINE 2
LINE 3
LINE 4
Примеры вызова
./print_lines.sh ex01_demo.txt– выводятся все строки файла (по умолчаниюn = 1)../print_lines.sh ex01_demo.txt 2– выводятся строкиLINE 2иLINE 4../print_lines.sh ex01_demo.txt 3– выводится строкаLINE 3../print_lines.sh ex01_demo.txt 5– нет вывода, так как в файле меньше пяти строк../print_lines.sh demo.txt -1– должна быть выведена ошибка, так как значениеnне является положительным.
Дополнительные требования:
- Проверять, что указанный файл существует, иначе выводить сообщение об ошибке и завершать работу.
- Проверять, что
n > 0, иначе выводить сообщение об ошибке и завершать работу. - Если второй аргумент отсутствует, использовать значение по умолчанию
n = 1.
Task description (English)
Write a Bash script called print_lines.sh that processes all lines of a given text file and outputs only selected lines.
- The name of the text file is passed as the first argument of the script.
- The second argument is optional and must be interpreted as a positive integer
n. - If the second argument is not provided, the script must use the default value
n = 1. - The script must then print every n-th line of the given text file.
Example file content
LINE 1
LINE 2
LINE 3
LINE 4
Example calls
./print_lines.sh ex01_demo.txt– print every line of the file (ndefaults to 1)../print_lines.sh ex01_demo.txt 2– print linesLINE 2andLINE 4../print_lines.sh ex01_demo.txt 3– print lineLINE 3../print_lines.sh ex01_demo.txt 5– no output, because the file does not contain enough lines../print_lines.sh demo.txt -1– print an error message, because the value fornis invalid (not positive).
Additional requirements:
- The script must check whether the given file exists and print an error message otherwise.
- The script must ensure that
n > 0; otherwise, it has to print an error message and exit. - If the second argument is missing, the script must use the default value
n = 1.
Solution – Bash script print_lines.sh
#!/bin/bash
# 1. Check that a file name was provided
if [ -z "$1" ]; then
echo "Error: no file name provided."
exit 1
fi
FILE="$1"
# 2. Check that the file exists
if [ ! -f "$FILE" ]; then
echo "Error: file '$FILE' does not exist."
exit 1
fi
# 3. Handle the second argument (n)
# If not given, use default n = 1
if [ -z "$2" ]; then
N=1
else
N="$2"
# N must be greater than 0
if [ "$N" -le 0 ]; then
echo "Error: n must be greater than 0."
exit 1
fi
fi
# 4. Main loop over all lines
LINE_NUM=0
while IFS= read -r LINE
do
LINE_NUM=$((LINE_NUM + 1))
# Print the line if its number is divisible by N
if [ $((LINE_NUM % N)) -eq 0 ]; then
echo "$LINE"
fi
done < "$FILE"