Score:2

Multiply found text in sed - is it possible?

sy flag

This is what I have:

echo -e "a\t4\nb\t7\nc\t2\nd\t12\n" | sed -rn 's/(.*)\t([0-9]*)$/\2\t\1\1\1\t/p'

4   aaa  
7   bbb 
2   ccc 
12  ddd 

This I want:

4   aaaa    
7   bbbbbbb  
2   cc  
12  dddddddddddd    

Is this possible in sed only or I have to use some other tools?

hr flag
It would certainly be *simpler* in other tools - perl for example has a string repetition operator ex. `printf '%c\t%d\n' a 4 b 7 c 2 d 12 | perl -F'\t' -lne 'print join "\t", $F[1], $F[0] x $F[1]'`
Raffa avatar
jp flag
I would go with @steeldriver perl script for sure.
xerostomus avatar
sy flag
You are right -- points up for Perl. :-) Thanks.
Score:3
jp flag

Not really totally pure sed, but rather with setting the flag e which allows for embedding shell commands and executing them and allows for risky command injection as well so know that one and do (if you have to) on your own risk.

Not really my preferred way either but you asked for it.

That said, you can do it with something like this:

$ echo -ne "a\t4\nb\t7\nc\t2\nd\t12\n" |
sed -rn "s/(.*)\t([0-9]*)$/bash -c \"printf '%s\t' \2; printf '\1%.0s' {1..\2}\"/ep"
4   aaaa
7   bbbbbbb
2   cc
12  dddddddddddd
hr flag
You could avoid the extra (bash) shell by using `seq` in place of the brace expansion in the replacement: `printf '%s\t' \2; printf '\1%.0s' \$(seq \2)`
Raffa avatar
jp flag
Yes, @steeldriver that would offer more portability … Although, starting an extra shell/sub-shell seems unavoidable both ways.
xerostomus avatar
sy flag
Raffa, I can do it to in Python or Bash, but I thought sed could be more elegant way. You are right that Perl is most elegant by now, but I do not know it much. I guess that awk could also do the job. I prefer to know less programming languages deeper then to know many languages superficially. So thank you all for nice jobs. :-)
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.