-1

How can repeat a word or line on a number of lines, like the command foo in

$ foo 3 word 
word
word
word

or

$ foo 2 An example line
An example line
An example line

with the same effect like

$ seq 3 | sed s/./word/
word
word
word

or

$ yes word | head -3
word
word
word

I had expected that seq supports that, but it does not, as far as I see.

0
2

You don't need any external utilities to do that, but just use your native shell's internals with printf() functionality. For e.g. in a bash shell, you could do

foo() {
    if [ "$1" -lt 2 ]; then
        printf '%s\n' 'insufficient arguments provided' >&2
    fi

    local iter
    for (( iter = 1; iter <= $1; iter++ )); do
        printf '%s\n' "$2"
    done
}

Make sure to quote the word to be printed under quotes, so that the words are not split. E.g.

foo 3 bar
foo 3 'howdy world'

If you are looking for an external utility for the same, perl or awk can just do it as needed

printf '%s\n' 'howdy world' | perl -ne 'print $_ x 3' 

or

printf '%s\n' 'howdy world' | awk '{ for (i = 1; i <= 3; i++) print $0 }'

Also BSD systems have a binary jot which can just repeat strings provided to it. Or in Ubuntu systems under athena-jot package.

jot -b 'howdy world' 3 
11
  • That approach works, but that would mean to build it myself. It would be faster than the two implementations I gave, but somewhat more complex. I think there must be a command that can do it alone. – Volker Siegel Jan 8 '20 at 6:20
  • @VolkerSiegel: The function gave uses nothing but the shell internals and no overhead at all. Any other external forked processes cannot match up to this – Inian Jan 8 '20 at 6:22
  • @VolkerSiegel: You can just add the function in .bashrc and just call it from the command line as you want – Inian Jan 8 '20 at 6:25
  • 1
    Yes! jot is exactly the command I am looking for! I started to give up the thought that it must exist for sure... I have it in Ubuntu! – Volker Siegel Jan 8 '20 at 7:22
  • 1
    It's actually worth being the first on top! That you found it is actually pretty emotional for me. I know UNIX in general pretty well. I have developed something like trust in it on the conceptual level. So I was sure this must exist... and it felt really deeply wrong that this does not exist. Now, it's only absurdly unknown, saves my worldview, thanks for digging it up. – Volker Siegel Jan 8 '20 at 7:36
1

tcsh and zsh have repeat:

repeat 3 echo word

With printf, you could do:

printf 'word\n%.0s' {1..3}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.