Shell - replace a string with an extra value

I have this line:

"a | a | a | a | a | a | a | a"

and I want to replace each "|" to the incremental value as follows:

"a0a1a2a3a4a5a6a"

I know that I can use gsub to replace strings:

> echo "a | a | a | a | a | a | a | a" | awk '{gsub(/\ \|\ /, ++i)}1'
a1a1a1a1a1a1a1a

But it seems that gsub only increases after each new line, so my solution will now first put a new line after each "|", and then use gsub again and delete the newline characters:

> echo "a | a | a | a | a | a | a | a" | awk '{gsub(/\ \|\ /, " | \n")}1' | awk '{gsub(/\ \|\ /, ++i)}1' | tr -d '\n'
a1a2a3a4a5a6a7a

It's honestly just disgusting ...

Is there a better way to do this?

+4
source share
4 answers

You can use awkas follows:

s="a | a | a | a | a | a | a | a"

awk -F ' *\\| *' -v OFS="" '{s=""; for(i=1; i<NF; i++) s = s $i i-1; print s $i}' <<< "$s"

a0a1a2a3a4a5a6a
  • -F ' *\\| *' |, .
  • for .
+3

perl :

$ echo 'a | a | a | a | a | a | a | a' | perl -pe 's/ *\| */$i++/ge'
a0a1a2a3a4a5a6a
  • *\| * |,
  • e Perl-
  • $i++ $i increment ( 0)
+7

, awk

echo "a | a | a | a | a | a | a | a" | 
awk -v RS="[ ]+[|][ ]+" '{printf "%s%s",(f?NR-2:""),$0; f=1}'

,

a0a1a2a3a4a5a6a
0

sh , , , :

s=$1  # first argument passed to script, "a | a | a |..."

n=0
while true
do
    prev=$s
    s=${s%" | a"}
    test "$s" = "$prev" && break
    result=$result${n}"a"
    n=$((n + 1))
done
echo $s$result

script digits.sh,

$ sh digits.sh "a | a | a | a | a | a | a | a"
a0a1a2a3a4a5a6a
$
0

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


All Articles