user2349253 user2349253 - 1 month ago 7
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

name,age,address,dob

Answer


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

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


With sed

$ echo "$columns" | sed 's/ [^,]*//g'
name,age,address,dob


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' 
name,age,address,dob

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}' 
name,age,address,dob