📅  最后修改于: 2023-12-03 14:39:27.807000             🧑  作者: Mango
Have you ever needed to print a specific line from a text file in Bash? This tutorial will show you how to do so using a simple script.
Our script will take in two arguments: the file path and the line number we want to print. Here's the code:
#!/bin/bash
file=$1
line_number=$2
sed -n "${line_number}p" $file
We start off by setting the file path and line number arguments in variables. The sed
command is then used to print the specific line number we want (${line_number}p
). The -n
flag suppresses the default printing behavior of sed
, and the $file
argument tells sed
to operate on the given file.
Save the script in a file with .sh
extension (for example, print_nth_line.sh
), make it executable with chmod +x
, and run it with the file path and line number arguments:
./print_nth_line.sh path/to/file.txt 5
This will print the 5th line of file.txt
.
Printing a specific line from a file in Bash is a simple task that can be accomplished with sed
. The script we've shown here can easily be modified to handle other similar use cases, such as printing a range of lines or printing specific patterns of text.