Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate Lines in Bash

Tags:

sed

awk

Most command-line programs just operate on one line at a time.

Can I use a common command-line utility (echo, sed, awk, etc) to concatenate every set of two lines, or would I need to write a script/program from scratch to do this?

$ cat myFile
line 1
line 2
line 3
line 4

$ cat myFile | __somecommand__
line 1line 2
line 3line 4
like image 531
Steven Avatar asked Oct 22 '10 15:10

Steven


People also ask

What does || mean in Linux?

datasoft@datasoft-linux:~$ cd gen && ls bash: cd: gen: No such file or directory datasoft@datasoft-linux:~$ cd gen && ls bash: cd: gen: No such file or directory. double vertical bar (||) The || represents a logical OR. The second command is executed only when the first command fails (returns a non-zero exit status).

How do I join two lines in Linux?

The traditional way of using paste command with "-s" option. "-d" in paste can take multiple delimiters. The delimiters specified here are comma and a newline character. This means while joining the first and second line use comma, and the second and third line by a newline character.

What does ${} mean in bash?

${} Parameter Substitution/Expansion A parameter, in Bash, is an entity that is used to store values. A parameter can be referenced by a number, a name, or by a special symbol.


4 Answers

sed 'N;s/\n/ /;'

Grab next line, and substitute newline character with space.

seq 1 6 | sed 'N;s/\n/ /;'
1 2
3 4
5 6
like image 148
Didier Trosset Avatar answered Oct 19 '22 18:10

Didier Trosset


$ awk 'ORS=(NR%2)?" ":"\n"' file
line 1 line 2
line 3 line 4

$ paste - -  < file
line 1  line 2
line 3  line 4
like image 34
ghostdog74 Avatar answered Oct 19 '22 19:10

ghostdog74


Not a particular command, but this snippet of shell should do the trick:

cat myFile | while read line; do echo -n $line; [ "${i}" ] && echo && i= || i=1 ; done
like image 38
kanaka Avatar answered Oct 19 '22 17:10

kanaka


You can also use Perl as:

$ perl -pe 'chomp;$i++;unless($i%2){$_.="\n"};' < file
line 1line 2
line 3line 4
like image 25
codaddict Avatar answered Oct 19 '22 18:10

codaddict