user2349253 user2349253 - 5 months ago 28
Bash Question

Unix Shell command for removing each words between space and comma

I have a string variable as

columns = "name string,age int,address string,dob timestamp"

I want to remove the datatypes. ie I want to remove the words coming after space and a comma. The output should be as



Assuming bash shell and extglob shell option is available - see pattern matching manual

$ columns='name string,age int,address string,dob timestamp'
$ echo "${columns// +([^,])/}"

With sed

$ echo "$columns" | sed 's/ [^,]*//g'

With awk to process fields separated by ,

$ echo "$columns" | awk -F, -v OFS="," '{for(i=1; i<=NF; i++){split($i,n," "); $i=n[1]}} 1' 

If all columns contain two words separated by space, one can use space or comma as delimiter and filter out unwanted fields

$ echo "$columns" | awk -F' |,' -v OFS=',' '{print $1,$3,$5,$7}'