Show certain lines by line number: Difference between revisions

From LemonWiki共筆
Jump to navigation Jump to search
(Created page with "Show certain lines by line number of string file == Testing text file == <pre> echo "line 1" > test.txt echo "line 2" >> test.txt echo "line 3" >> test.txt echo "line 4" >> t...")
 
Tags: Mobile edit Mobile web edit
Line 1: Line 1:
Show certain lines by line number of string file
Show certain lines by line number of string file


== Testing text file ==
== Prepare the testing text file ==
<pre>
<pre>
echo "line 1" > test.txt
echo "line 1" > test.txt

Revision as of 11:51, 1 December 2019

Show certain lines by line number of string file

Prepare the testing text file

echo "line 1" > test.txt
echo "line 2" >> test.txt
echo "line 3" >> test.txt
echo "line 4" >> test.txt
echo "line 5" >> test.txt
echo "line 6" >> test.txt

Approaches

Using cat, head & tail commands

1. key-in the command[1]

# X: start line number
# Y: end line number
X=2
Y=4
Z=$(($Y-$X+1))
cat test.txt | head -n $Y | tail -n $Z

result

line 2
line 3
line 4

2. key-in the command if you want to show the line number of each line

# X: start line number
# Y: end line number
X=2
Y=4
Z=$(($Y-$X+1))
cat -n test.txt | head -n $Y | tail -n $Z

result

     2	line 2
     3	line 3
     4	line 4

Using sed command

key-in the command[2]

# X: start line number
# Y: end line number
X=2
Y=4
Z=$(($Y-$X+1))
sed -n -e "$X,$Y p" -e "$Y q" test.txt

result

line 2
line 3
line 4

References