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

Posted on In QA

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

a
good
boy

to

a good boy

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 by Lukáš Šníder.

Another method using paste:

paste -sd ' ' < file.txt

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *