Substring substitution in bash
Asked Answered
S

4

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?

Sister answered 7/12, 2014 at 17:55 Comment(0)
N
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 //.

Nabokov answered 7/12, 2014 at 17:56 Comment(1)
Or without backslashes: o=${s%%//*};while [[ $s != ${str#*//} ]] ;do o+=,${s%%//*}; s=${s#*//};done;o+="$s"Starlin
T
1

You can use sed as

$ echo "6427//6422 6429//6423 6428//6421" | sed 's#//#,#g'
6427,6422 6429,6423 6428,6421
Tachygraphy answered 7/12, 2014 at 17:57 Comment(0)
B
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
Brochu answered 7/12, 2014 at 20:50 Comment(0)
T
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.

Tude answered 15/3, 2023 at 15:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.