user2349253 user2349253 - 1 year ago 58
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


Answer Source

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}' 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download