1

I'm trying to replace a fixed parse ("replaceMe") in a text with multi-lined text with sed. My bash script goes as follows:

content=$(awk'{print $5}' < data.txt | sort | uniq)
target=$(cat install.sh)
text=$(sed "s/replaceMe/$content/" <<< "$target")
echo "${text}"

If content contains one line only, replacing works, but if it contains sevrel lines I get:

sed:... untarminated `s' command

I read about "fetching" multi-lined content, but I couldn't find something about placing multi lined string

Inian
  • 80,270
  • 14
  • 142
  • 161
  • 1
    `sed` terminates commands with a newline. You can't reliably use multiline with sed. – KamilCuk Jun 24 '19 at 11:26
  • By `awk'{print $5}' < data.txt | sort | uniq` - do you REALLY need to sort that input or are you just trying to get the unique values but the order doesn't matter? – Ed Morton Jun 24 '19 at 11:27
  • @EdMorton Order does not matter... I read somewhere that you should 'sort' before 'uniq' – Alaychem goes to Codidact Jun 24 '19 at 11:30
  • Yes `uniq` only works on contiguous identical values such as you'd get from sorted input but `sort | uniq` is equivalent to just `sort -u` and you don't need either to just get unique values when you're using awk (e.g. `awk '!seen[$0]++' file` alone outputs the unique values from `file`) which is why I was asking. – Ed Morton Jun 24 '19 at 11:48

1 Answers1

1

You'll have more problems than that depending on the contents of data.txt since sed doesn't understand literal strings (see Is it possible to escape regex metacharacters reliably with sed). Just use awk which does:

text="$( awk -v old='replaceMe' '
    NR==FNR {
        if ( !seen[$5]++ ) {
            new = (NR>1 ? new ORS : "") $5
        }
        next
    }
    s = index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+length(old)) }
    { print }
' data.txt install.sh )"
Ed Morton
  • 188,023
  • 17
  • 78
  • 185