Turning multiple lines into one comma separated line
Using paste command:
paste -d, -s file
Turning multi-line string into single comma-separated
You can use awk
and sed
:
awk -vORS=, '{ print $2 }' file.txt | sed 's/,$/\n/'
Or if you want to use a pipe:
echo "data" | awk -vORS=, '{ print $2 }' | sed 's/,$/\n/'
To break it down:
awk
is great at handling data broken down into fields-vORS=,
sets the "output record separator" to,
, which is what you wanted{ print $2 }
tellsawk
to print the second field for every record (line)file.txt
is your filenamesed
just gets rid of the trailing,
and turns it into a newline (if you want no newline, you can dos/,$//
)
How to concatenate multiple lines of output to one line?
Use tr '\n' ' '
to translate all newline characters to spaces:
$ grep pattern file | tr '\n' ' '
Note: grep
reads files, cat
concatenates files. Don't cat file | grep
!
Edit:
tr
can only handle single character translations. You could use awk
to change the output record separator like:
$ grep pattern file | awk '{print}' ORS='" '
This would transform:
one
two
three
to:
one" two" three"
How to convert multiple words in single line separated by comma in list of multiple lines
echo "your string" |tr \[ ' '|tr \] ' '|tr , \\n|awk '{$1=$1};1'
Explanation
echo "your string"
prints your string, then piped to the nexttr
tr \[ ' '
substitutes [ with an empty spacetr \] ' '
substitutes ] with an empty spacetr , \\n
substitutes the comma with a newlineawk '{$1=$1};1'
(taken from here) trims spaces
How to join multiple lines of file names into one with custom delimiter?
Similar to the very first option but omits the trailing delimiter
ls -1 | paste -sd "," -
Related Topics
Bash Sort - How to Sort Using Timestamp
Shell Script for Multithreading a Process
Find the Files Existing in One Directory But Not in the Other
How to Check in Bash Whether a File Was Created More Than X Time Ago
Fork: Retry: Resource Temporarily Unavailable
How to Know If I'm Running a Nested Shell
Expand a Possible Relative Path in Bash
Linux - Understanding the Mount Namespace & Clone Clone_Newns Flag
Genymotion Throws Libssl_Conf.So: Cannot Open Shared Object File: No Such File or Directory
Set Filetype and Comment Key Map with .S File
Copy Differences Between Two Files in Unix
How to Grep a String in a Directory and All Its Subdirectories
Unix - Count of Columns in File
Must My Pidfile Be Located in /Var/Run
Grep Recursively for a Specific File Type on Linux