简体   繁体   中英

bash- remove \n every three lines

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

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

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.

awk 'NR%3==2{printf "%s ",$0;next}{print $0}' input.txt

Output:

1
name John
2
family Grady
3
Tel 123456

You could do this in Perl,

$ perl -pe 's/\n/ /g if $. % 3 == 2' file
1
name John
2
family Grady
3
Tel 123456

一种使用AWK的方法:

awk '{ printf "%s%s", $0, (NR%3==2 ? FS : RS) }' file

Yet another solution, in Bash:

while read line
do
  if [[ $line = *: ]]
  then
    echo -n $line
  else
    echo $line
  fi
done < input.txt

Unix way:

$ paste -sd'\n \n' input

Output:

1
name John
2
family Grady
3
Tel 123456

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM