Saturday, 29 September 2012

How to concatenate multiple lines in console (bash, cmd)

If for some reasons you need to have concatenated lines try one of the recipes below.



Unix world


1. Seamed concatenation


seq 6 | xargs

This is the shortest command. It concatenates all input strings using a space character as a glue. Only the space. So if you need another character you can try one of the commands like below. They concatenates multiple lines into one using a comma character. Just replace it with the more preferrable character in your situation.

seq 6 | paste -sd','
seq 6 | sed ':a;N;s/\n/,/;ta'
seq 6 | perl -pe 's/\n$/,/'

Each command from above has their own features. For eaxample paste allows usage of several different gluing characters. The code below is produce the string 1q2w3e4r5t6:

seq 6 | paste -sd'qwerty'

sed and perl are possible to concatenate by a string as well.

2. Seamless concatenation


If you need to concatenate strings without gluing characters or strings just try one of the commands:

seq 6 | tr -d \\n
seq 6 | perl -pe 'chomp'
seq 6 | perl -pe 's/\n$//'
seq 6 | sed ':a;N;s/\n//;ta'

Unix way is good way. If you can do something you can do it by a lot of ways. But let's consider this issue in Windows.

Windows world


Windows habitants fond of VBScript. Let's see it first:

lines = WScript.StdIn.ReadAll()
glued = Replace(lines, Chr(13) & Chr(10), "")
WScript.Echo glued

Programming in JScript is good practice. Fortunately it is bundled in Windows. Another reason to use JScript instead VBScript is availibility to bundle JScript within Batch file so it can be ran directly (See here and here to know how to bundle JScript into Batch file).

var lines = WScript.StdIn.ReadAll();
var glued = lines.replace(/\r\n/g, '');
WScript.Echo(glued);

Finally, there is PowerShell. It is weird attempt of implementing Unix way in Windows world:

powershell -join $input

Conclusion

We see that Unix gives many ways to obtain required result. It is very good approach. There is couple of valid ways in Windows. It is better than nothing. You can improve you state installing one of good packages: Cygwin, GnuWin32, or UnixUtils. Once installing one of them you will get powerful toolkit making you closer to Unix.

No comments:

Post a Comment