Eduardo
Eduardo

Reputation: 397

Join Merge only the first two lines of a file using AWK or SED

I have a file like this

Line1
Line2
Line3
Line4
Line5

I need the output like this:

Line1Line2
Line3
Line4
Line5

I tried sed ":a;N;$!ba;s/\n//g" asd.txt but it combines all lines into one.

Upvotes: 0

Views: 208

Answers (4)

Steve
Steve

Reputation: 54402

Using sed you can restrict an operation to a specific line number. In this case, we are restricting the append (to pattern space) and substitution to line 1:

sed '1 {N; s/\n//}' file

Note that this solution could also be written without the braces:

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

But please note that this last solution is somewhat less maintainable. Whether or not that's problematic for you is another thing. In either case, the results are:

Line1Line2
Line3
Line4
Line5

Upvotes: 2

repzero
repzero

Reputation: 8412

sed '1 {N;s/\n//}'

results

Line1Line2
Line3
Line4
Line5

take line 1 and add the next line to it . Afterwards remove the newline character

Upvotes: 0

nu11p01n73R
nu11p01n73R

Reputation: 26667

An awk solution would be like

$ awk '{ORS=(NR==1?"":"\n")}1 ' input
Line1Line2
Line3
Line4
Line5

OR

$ awk '{ORS=(NR==1?"":RS)}1 ' input
Line1Line2
Line3
Line4
Line5

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174706

You could try the below sed command,

$ sed 'N;0,/\n/s/\n//' file
Line1Line2
Line3
Line4
Line5

N appends the next line into pattern-space. 0,/./ (specifies the range) which helps to do the replacement on the first match only. s/\n// replaces the first newline character with an empty string.

Upvotes: 0

Related Questions