Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pair every two lines of a text file with Bash? [duplicate]

With a simple bash script I generate a text file with many lines like this:

192.168.1.1
hostname1
192.168.1.2
hostname2
192.168.1.3
hostname3

Now I want to reformat this file so it looks like this:

192.168.1.1 hostname1
192.168.1.2 hostname2
192.168.1.3 hostname3

How would I reformat it this way? Perhaps sed?

like image 757
fwaechter Avatar asked Oct 03 '09 14:10

fwaechter


People also ask

How do you join two lines in bash?

A short Bash one-liner can join lines without a delimiter: $ (readarray -t ARRAY < input. txt; IFS=''; echo "${ARRAY[*]}") I cameI sawI conquered!

What is || in scripting?

4. OR Operator (||) The OR Operator (||) is much like an 'else' statement in programming. The above operator allow you to execute second command only if the execution of first command fails, i.e., the exit status of first command is '1'.

What is double colon in Bash?

It's nothing, these colons are part of the command names apparently. You can verify yourself by creating and running a command with : in the name. The shell by default will autoescape them and its all perfectly legal. Follow this answer to receive notifications.


3 Answers

$ sed '$!N;s/\n/ /' infile 192.168.1.1 hostname1 192.168.1.2 hostname2 192.168.1.3 hostname3 
like image 90
Tim Avatar answered Oct 16 '22 12:10

Tim


I love the simplicity of this solution

cat infile | paste -sd ' \n'

192.168.1.1 hostname1
192.168.1.2 hostname2
192.168.1.3 hostname3

or make it comma separated instead of space separated

cat infile | paste -sd ',\n'

and if your input file had a third line like timestamp

192.168.1.1
hostname1
14423289909
192.168.1.2
hostname2
14423289910
192.168.1.3
hostname3
14423289911

then the only change is to add another space in to the delimiter list

cat infile | paste -sd '  \n'

192.168.1.1 hostname1 14423289909
192.168.1.2 hostname2 14423289910
192.168.1.3 hostname3 14423289911
like image 45
rob Avatar answered Oct 16 '22 12:10

rob


Here's a shell-only alternative:

while read first; do read second; echo "$first $second"; done
like image 36
Jukka Matilainen Avatar answered Oct 16 '22 12:10

Jukka Matilainen