cat command to print multiple lines from a text file



JasKinasis

Well-Known Member
Credits
3,323
Not using cat. But you could use sed, or awk, or a combination of head and tail to print specific lines.
E.g.

sed:
Bash:
sed -n '25p;45p;65p' temp4.txt
awk:
Bash:
awk 'NR==25 || NR==45 || NR==65' temp4.txt
head and tail:
Bash:
head -25 temp4.txt | tail +25
head -45 temp4.txt | tail +45
head -65 temp4.txt | tail +65
Note: All of the above are completely off the top of my head because I’m on my phone. I haven’t tested them on my laptop or anything because I don’t have it with me. But the syntax should be correct.
However, apologies if any of them aren’t quite right!
 
Last edited:

JasKinasis

Well-Known Member
Credits
3,323
Aha - I see what is wrong. Because I wrote the post on my phone, it used the wrong single quote characters. So when you copy/pasted it didn't like the single quote characters!
I'll edit the snippets in my original post, to correct them.

I've tested my original snippets and all three methods work for me on Debian 10. The problem was the quotation marks were incorrect.
 
Last edited:

wizardfromoz

Super Moderator
Staff member
Gold Supporter
Credits
6,153
Congratulations, moving this to Command Line, to tidy up.

Wizard
 

research1695

New Member
Credits
61
A follow up question on the sed command:

Bash:
sed -n '25p;45p;65p' temp4.txt

I actually need to print more lines with the same pattern (+20) until line 30025, I currently have the above command with all numbers written out till 30025, that command is pretty long (although it works), is there a shortcut?
 

JasKinasis

Well-Known Member
Credits
3,323
I know in bash you can generate a sequence of numbers in steps using the seq command.
So to get each number from 25 to 30025 in steps of 20, you would use:
Bash:
seq 25 20 30025
Where 25 is the first number, 20 is the increment/interval and 30025 is the highest number to generate.

Plugging that into a short script, you could do this:
Bash:
#!/usr/bin/env bash

for i in $(seq 25 20 30025)
do
  sed -n "$i p" temp4.txt
done
That would involve invoking sed a lot of times, but is the only solution I can think of, off the top of my head. For each number in the sequence, we call sed and print the specified line.

There may be a way to allow us to put the sequence into a single sed command, but I can't quite work it out ATM.....
 


Members online


Top