Reputation: 191
How can I remove newline delimiter from every three lines. Example:
input:
1
name
John
2
family
Grady
3
Tel
123456
output:
1
name John
2
family Grady
3
Tel 123456
Upvotes: 1
Views: 3080
Reputation: 2612
Unix way:
$ paste -sd'\n \n' input
Output:
1
name John
2
family Grady
3
Tel 123456
Upvotes: 0
Reputation: 882146
Assuming all those lines you want joined with the next one end with :
(your original question):
1
name:
John
2
family: Grady
3
Tel:
123456
You can use sed
for this, with:
sed ':a;/:$/{N;s/\n//;ba}'
The a
is a branch label. The pattern :$
(colon at end of line) is detected and, if found, N
appends the next line to the current one, the newline between them is removed with the s/\n//
substitution command, and it branches back to label a
with the ba
command.
For your edited question where you just want to combine the second and third line of each three-line group regardless of content:
1
name
John
2
family
Grady
3
Tel
123456
Use:
sed '{n;N;s/\n/ /}'
In that command sequence, n
will output the first line in the group and replace it with the second one. Then N
will append the third line to that second one and s/\n/ /
will change the newline between them into a space before finally outputting the combined two-three line.
Then it goes onto the next group of three and does the same thing.
Both those commands will generate the desired output for their respective inputs.
Upvotes: 2
Reputation: 58488
This might work for you (GNU sed):
sed 'n;N;s/\n//' file
to replace the newline with a space use:
sed 'n:N;s/\n/ /' file
as an alternative use paste:
paste -sd'\n \n' file
Upvotes: 3
Reputation: 174796
You could do this in Perl,
$ perl -pe 's/\n/ /g if $. % 3 == 2' file
1
name John
2
family Grady
3
Tel 123456
Upvotes: 2
Reputation: 7844
awk 'NR%3==2{printf "%s ",$0;next}{print $0}' input.txt
Output:
1
name John
2
family Grady
3
Tel 123456
Upvotes: 2
Reputation: 54532
One way using AWK:
awk '{ printf "%s%s", $0, (NR%3==2 ? FS : RS) }' file
Upvotes: 2
Reputation: 249464
Yet another solution, in Bash:
while read line
do
if [[ $line = *: ]]
then
echo -n $line
else
echo $line
fi
done < input.txt
Upvotes: 0