Given a Set of String, the task is to convert the Set to a comma separated String in Java. Approach: This can be achieved with the help of join() method of String as follows. Get the Set of String. Form a comma separated String from the Set of String using join() method by passing comma ', ' and the set as parameters.
The paste command can merge lines from multiple input files. By default, it merges lines in a way that entries in the first column belong to the first file, those in the second column are for the second file, and so on. The -s option can let it merge lines row-wise.
Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.
You can use while shell loop to read comma-separated cvs file. IFS variable will set cvs separated to , (comma). The read command will read each line and store data into each field.
Clean and simple:
awk '{print $2}' file.txt | paste -s -d, -
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 }
tells awk
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 do s/,$//
)cat data.txt | xargs | sed -e 's/ /, /g'
This might work for you:
cut -d' ' -f5 file | paste -d',' -s
+12.0,+15.5,+9.0,+13.5
or
sed '/^.*\(+[^ ]*\).*/{s//\1/;H};${x;s/\n/,/g;s/.//p};d' file
+12.0,+15.5,+9.0,+13.5
or
sed 's/\S\+\s\+//;s/\s.*//;H;$!d;x;s/.//;s/\n/,/g' file
For each line in the file; chop off the first field and spaces following, chop off the remainder of the line following the second field and append to the hold space. Delete all lines except the last where we swap to the hold space and after deleting the introduced newline at the start, convert all newlines to ,
's.
N.B. Could be written:
sed 's/\S\+\s\+//;s/\s.*//;1h;1!H;$!d;x;s/\n/,/g' file
$ awk -v ORS=, '{print $2}' data.txt | sed 's/,$//'
+12.0,+15.5,+9.0,+13.5
$ cat data.txt | tr -s ' ' | cut -d ' ' -f 2 | tr '\n' ',' | sed 's/,$//'
+12.0,+15.5,+9.0,+13.5
awk one liner
$ awk '{printf (NR>1?",":"") $2}' file
+12.0,+15.5,+9.0,+13.5
This should work too
awk '{print $2}' file | sed ':a;{N;s/\n/,/};ba'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With