Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

Replace text with values from array in Bash

I'm trying to replace words with values from an array with "sed". The problem is that the array has a different length for each file, 0, 1 or 9 values. When replacing, the values should be separated with a comma. For example:

array = (one two three)
sed -e "s | value = " text to replace  "| value = " $ {array (*)}  "| g"
the result should look like this: value = one, two, three
and if array = (one) => value = one

Can someone help me please? thank you in advance!

question from:https://stackoverflow.com/questions/65902779/replace-text-with-values-from-array-in-bash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

bash variable assignments must not have spaces around the =

array=(one two three)

To join using a single character, IFS is your friend:

IFS=,

# .....v.......................................v.............v...v
sed -e 's/value = " text to replace "/value = "'"${array[*]}"'"/g'
# ..............................................^^^^^^^^^^^^^

My quoting is very deliberate there. I've marked where the single quotes start and stop, and the array expansion must be enclosed in double quotes.

Overall, you were pretty close. Have to be careful with the whitespace, bash can be very sensitive to it.


IFS is the shell's "internal field separator" -- it is used to

  • split a string into fields

    line="foo,bar:baz"
    IFS=':,'
    read first second third <<<"$line"
    declare -p first second third
    
  • join array elements into a single string

    set -- a b c d
    IFS=':,'
    echo "$*"     # _must_ be quoted
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...