Convert Multiple Rows into Single Row in Linux
In this article, we are going to see how to convert multiple rows into a single row using Linux.
Here is the file for demonstration:
Method 1: Using Pure Bash
Let us convert multiple rows into a single row using pure bash since it is the default shell, please make a note that bash shell does not depend on other utilities as it makes use of only built-in commands :
We use the above input file as a template to perform our desired operation i.e converting multiple rows into a single row in Linux.
Syntax: $ (readarray -t ARRAY < inputfile.txt; IFS=”; echo “${ARRAY[*]}”)
Where:
- The readarray is a Bash built-in command. It was introduced in Bash ver.4. The readarray is used for reading inputs standard input into an array variable: ARRAY.
- The -t option is handy for removing
- The IFS is a special shell variable which ia an abbreviation for Internal Field Separator. Here, we assigned the IFS with a single character, empty or ‘,’ depends on our requirements.
- ${ARRAY[*]} means all elements surrounded in ARRAY variable, by using the echo command, all elements of ARRAY will be printed out which are separated by the IFS variables.
Example:
$ (readarray -t ARRAY < newfile.txt; IFS=''; echo "${ARRAY[*]}")
Output :
Method 2: Using tr command
tr is a command which is handy at deletion and translation of specific characters fetched from the standard input file.
Syntax: $ tr [OPTION] SET1 [SET2]
The tr command can simply do this job by simply by removing line breaks from the file content.
Example:
$ tr -d '\n' ',' <newfile.txt
Output :
Method 3: Using Paste command
Paste command is handy for joining files horizontally by outputting lines consisting of lines from each file specified.
Syntax : paste [OPTION]… [FILES]…
The paste command is used for merging lines belonging to multiple input files. This Merging operation by default is executed in such a way that entries in the first column belong to the first file, and the ones in the second column are for the second file.The -s option can let it merge lines row-wise.
Example:
$ paste -sd ',' newfile.txt
Output :
Method 4: Using sed command
Sed in Unix is an abbreviation for stream editor, which is handy in executing different kinds of operations like searching, find and replace, insertion or deletion.
Syntax : sed OPTIONS… [SCRIPT] [INPUTFILE…]
Here, the motto of using sed one-liner is: append each line into the pattern space, at last replace all line breaks with the given string.
Example:
$ sed ':a; N; $!ba; s/\n/,/g' newfile.txt
Output :
Please Login to comment...