Home > Software engineering >  sed or awk, removing curly brackets but only if there are no commas inside brackets
sed or awk, removing curly brackets but only if there are no commas inside brackets

Time:08-24

i have a string and need to remove { and } if there is no comma inside curly brackets,

string:

ex00/{ft_strdup.c} ex04/{ft_convert_base.c,ft_convert_base2.c} ex05/{ft_split.c}

want to create these files with touch, curly brackets work for multiple files but gives error at single file, how can i remove brackets if there is no comma (meaning single file)?

thanks

desired output:

ex00/ft_strdup.c ex04/{ft_convert_base.c,ft_convert_base2.c} ex05/ft_split.c

to explain what is task of script: i have a txt file and inside it have such lines:

Turn-in directory : ex06/

Files to turn in : ft_this.c, ft_that.h

Turn-in directory : ex07/

Files to turn in : ft_test.c

now i need to create these files with touch

files=$(cat subject.txt \
| grep "Turn-in directory\|Files to turn in" \
| tr -d ' ' \
| awk -F: '{print $2 "}"}' \
| tr -d '\n' \
| sed 's/ex/ ex/g' \
| sed 's/\//\/\{/g' \
| sed 's/{}/{/g')

eval "touch $files"

CodePudding user response:

Using any sed:

$ sed 's/{\([^,}]*\)}/\1/g' file
ex00/ft_strdup.c ex04/{ft_convert_base.c,ft_convert_base2.c} ex05/ft_split.c

Note that the above will work no matter which characters except ,, {, }, or \n exist in your file names, e.g. these are all valid file names:

$ cat file
ex00/{ft_strdup1.c} ex05/{ft-split.c} ex05/{ft=s&pl#it.c}

$ sed 's/{\([^,}]*\)}/\1/g' file
ex00/ft_strdup1.c ex05/ft-split.c ex05/ft=s&pl#it.c

If your file names can contain any of the characters I mentioned above as excluded then ask a new question including those in your sample input/output.

CodePudding user response:

Using sed

$ sed -E 's/\{([[:alpha:]_.] )}/\1/g' input_file
touch ex00/ft_strdup.c ex04/{ft_convert_base.c,ft_convert_base2.c} ex05/ft_split.c

CodePudding user response:

With your shown samples please try following awk code. Written and tested in GNU awk.

awk -v RS='{[^}]*}' '
RT{
  if(!sub(/,/,"&",RT)){ gsub(/^{|}$/,"",RT) }
}
{ ORS=RT }
1
END{ print "" }
'  Input_file

CodePudding user response:

This might work for you (GNU sed):

sed 's/{\([^,]*\)}/\1/g' file

Match globally on a pair of curly braces only when the contents between them does not contain a comma and replace the match by the contents.

  • Related