Substitution substitution in bash

my problem today is replacing in a line like this, → 6427//6422 6429//6423 6428//6421

each // with a,. I tried with various commands:

  • finalString=${startingString//[//]/,} does not work
  • fileTemp=$(echo -e "$line\n" | tr "//" "," performs double substitution:

    hello//world ---> hello,,world

Does anyone have an idea how to do this?

+6
source share
3 answers

You can use BASH string manipulations (you need to exit / with \/ ):

 s='6427//6422 6429//6423 6428//6421' echo "${s//\/\//,}" 6427,6422 6429,6423 6428,6421 

Similarly, using awk:

 awk -F '//' -v OFS=, '{$1=$1}1' <<< "$s" 6427,6422 6429,6423 6428,6421 

PS: tr cannot be used here, since tr translates each character in the input of another character in the output, and here you are dealing with 2 // characters.

+3
source

You can use sed as

 $ echo "6427//6422 6429//6423 6428//6421" | sed 's#//#,#g' 6427,6422 6429,6423 6428,6421 
+1
source

You can also try sed command like this

 sed 's#/\{2,2\}#,#g' 

finds a double "/" and replaces with a ","

Example

 echo "6427//6422 6429//6423 6428//6421"| sed 's#/\{2,2\}#,#g' 

results

 6427,6422 6429,6423 6428,6421 
+1
source

Source: https://habr.com/ru/post/979251/


All Articles