6

my problem of today is to replace in a string like this --> 6427//6422 6429//6423 6428//6421

every // with a ,. I tried with different commands:

  • finalString=${startingString//[//]/,} doesn't work
  • fileTemp=$(echo -e "$line\n" | tr "//" "," does a double substitution like this:

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

Someone has an idea of a way to do it?

Mattia Baldari
  • 567
  • 1
  • 5
  • 15

4 Answers4

3

You can use BASH string manipulations (need to escape / 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 input to another character in the output and here you're dealing with 2 characters //.

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

You can use sed as

$ echo "6427//6422 6429//6423 6428//6421" | sed 's#//#,#g'
6427,6422 6429,6423 6428,6421
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
1

You can also try the sed command like this

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

finds double "/" and replace with ","

Example

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

Results

6427,6422 6429,6423 6428,6421
repzero
  • 8,254
  • 2
  • 18
  • 40
1

You could use tr:

echo "6427//6422 6429//6423 6428//6421" | tr -s '/' ','
6427,6422 6429,6423 6428,6421

Note the addition of the -s flag, an alias for --squeeze-repeats:

Replace each input sequence of a repeated character that is listed in SET1 with a single occurrence of that character.

Lee
  • 29,398
  • 28
  • 117
  • 170