Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How join several lines in a file? 2

Status
Not open for further replies.

inma

Technical User
Apr 5, 2001
49
ES
Hi, I have a txt file which contains serveral lines, and I want delete the newline character to join them.
Can anybody help me?
Thanks
 
bash solution

while read line; do echo -n $line ;done < testinput

awk solution

awk '{printf $0}' testinput

Cheers,
Pravin.
 
There is already a command to do exactly what you want called &quot;paste&quot;, use the -s option to combine subsequent lines of the input file.

e.g.
paste -s -d ' ' file1 > file2

The -d option allows you to specify a delimiter.

 
Thanks for your reply.
Now I only want to delete the newline character of lines not starting with # character.

 
I have solution but its not completely correct. Try if it works for your input file.

Code:
awk '/^#/{printf &quot;\n&quot;$0&quot;\n&quot;;next}{printf $0&quot; &quot;}' testinput
Cheers,
Pravin.
 
Thanks very much Pravin, it works very well!!
 
Hi inma,
Good to know your problem has been solved. Anyway now that I have found it here is a cleaner solution.

awk '/^#/{if (a==&quot;&quot;) {printf $0&quot;\n&quot;} else {printf a&quot;\n&quot;$0&quot;\n&quot;}; a=&quot;&quot;;next} {(a==&quot;&quot;)?a=$0:a=a&quot; &quot;$0}' testinput

Cheers,
Pravin.
 
Now I don`t want that a newline goes before the first # character of the first line.
What must I do?
Thanks
 
Code:
awk '/^#/ {printf(&quot;%s%s\n&quot;, nl, $0); sp=&quot;&quot;; nl=&quot;&quot;; next} {printf(&quot;%s%s&quot;, sp, $0); sp=&quot; &quot;; nl=&quot;\n&quot;}' testinput

Some comments:
If the previous line started with a # (or we are at start of file), nothing to add at start of current line (sp=&quot;&quot;; nl=&quot;&quot;)
If the previous line did not start with a #, add a space before current line if it does not start with a # (sp=&quot; &quot;) and a newline if it starts with a # (nl=&quot;\n&quot;).
 
Thanks very much dchoulette, it works very well!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top