Reputation: 1105
How can I clean in bash the following line
-,2,8,--,-,2,6,--,-,-1,2,--,-,0,4,--,-,1,5,--,-,-5,2
in order to get
2,8,2,6,-1,2,0,4,1,5,-5,2
I only want positive and negative numbers separated by comma
Upvotes: 0
Views: 64
Reputation: 180103
You can run it through this sed
script:
sed -e 's/--*,//g' -e 's/,--*$//'
That wipes out every substring consisting of one or more minus signs (-
) followed by a comma (,
), and, separately, any trailing substring consisting of a comma followed by one or more minus signs.
Upvotes: 2
Reputation: 203229
$ awk 'BEGIN{FS=OFS=","} {j=0; for (i=1;i<=NF;i++) if ($i~/^-?[0-9]/) printf "%s%s", (++j>1?OFS:""), $i; print ""}' file
2,8,2,6,-1,2,0,4,1,5,-5,2
Loop through each field, testing if the current field is a number optionally preceded with -
. If it is then print the field preceded by nothing if it's the first matching field on the line or by the output field separator otherwise. When done printing the fields print a newline.
Upvotes: 0
Reputation: 784998
A gnu-awk solution:
str='-,2,8,--,-,2,6,--,-,-1,2,--,-,0,4,--,-,1,5,--,-,-5,2'
awk -v FPAT='-?[0-9]+' '{for(i=1; i<=NF; i++) printf "%s%s", $i, (i<NF)?",":RS}' <<< "$str"
2,8,2,6,-1,2,0,4,1,5,-5,2
A non-gnu awk solution:
str=$(awk 'BEGIN{RS=ORS=","} /^-?[[:digit:]]+/{print $1}' <<< "$str")
Output:
echo "${str%,}"
2,8,2,6,-1,2,0,4,1,5,-5,2
Upvotes: 1
Reputation: 2191
try:
egrep -o "\-?[0-9]+" | sed ':a;N;$!ba;s/\n/,/g'
or:
egrep -o "\-?[0-9]+" | xargs | sed 's/ /,/g'
Upvotes: 0