adgalad
adgalad

Reputation: 75

BASH: print two lines of a file in the same line

I'm try to print with bash two lines of a text file in the same line and with only one command.

for example, if you have the next file and you want the lines 1 and 3

Cat
Bye
Bash
Dog
Hello

then you need a command that returns the following

$ cmd
Cat Bash

Is that possible? I try with

$ sed -n '1,3{p;n;}' [FILENAME] 

but it prints the two lines of text in two different lines, like:

Cat
Bash

thanks

Upvotes: 3

Views: 4269

Answers (3)

Robin Hsu
Robin Hsu

Reputation: 4514

This should work:

echo `sed -n '3,5{p;n;}' [FILENAME]`

Just an extra 'echo' with command substitution `` to join the lines.

Upvotes: 0

potong
potong

Reputation: 58578

This might work for you (GNU sed):

sed '1H;3H;$!d;x;s/\n//;y/\n/ /' file

In general append required lines to the hold space (HS) and delete all lines except the last. On the last line swap to the HS, delete the first newline and translate all other newlines to spaces.

N.B. The lines to be collected can be stated in any order as long as they come before the address for the last line. If the order of the collection is known the method can be shortened to:

sed '1h;2H;$!d;x;y/\n/ /' file

Upvotes: 0

John1024
John1024

Reputation: 113994

$ sed -n '1 h; 3{x;G;s/\n/ /;p}' fname
Cat Bash

Explanation

  • -n

    This tells sed not to print anything unless we explicitly ask it to.

  • 1 h

    When we reach line 1, this tells sed to save it in the 'hold' space.

  • 3 {x;G;s/\n/ /;p;}

    When we reach line 3, we do the following:

    • x exchanges the pattern space and hold space. When this is done, the pattern space has line 1 and the hold space has line 5.

    • G appends the hold space to the pattern space. When this is done, the pattern space has lines 1 and 3.

    • s/\n/ / replaces the newline character that separates line 1 and line 3 with a space. When this is done, the data from lines 1 and 3 are on the same line.

    • p tells sed to print the result.

On Mac OSX, try:

sed -n -e '1 h' -e '3{x;G;s/\n/ /;p;}' fname

Upvotes: 1

Related Questions