In Bash script, how to join multiple lines from a file?

In Bash script, how to join multiple lines from a file? For example, to join the lines

a
good
boy

to

a good boy
asked Oct 18, 2016 by anonymous

1 Answer

You can use tr command, something like:

tr -s '\n' ' ' < file.txt

It just goes through its input and makes changes according to what you specify in two sets ('\n' ' ' in this case, we change each newline to a space), -s is there, in case of empty lines (more newline) which will be squeezed into one space.
Also you need to use redirection < as tr by default does't take file as an argument.

answered Nov 5, 2016 by Lukáš Šníder (140 points)

Another method using paste:

paste -sd ' ' < file.txt

commented Nov 13, 2016 by Eric Z Ma (44,280 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...