Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring substitution in bash

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?

like image 771
Mattia Baldari Avatar asked Dec 07 '14 17:12

Mattia Baldari


3 Answers

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 //.

like image 93
anubhava Avatar answered Oct 02 '22 07:10

anubhava


You can use sed as

$ echo "6427//6422 6429//6423 6428//6421" | sed 's#//#,#g'
6427,6422 6429,6423 6428,6421
like image 25
nu11p01n73R Avatar answered Oct 02 '22 09:10

nu11p01n73R


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
like image 29
repzero Avatar answered Oct 02 '22 08:10

repzero