Bash Script to repeat every word in a line?

Adding to the family of solutions :-) .

duplicator.sh:

for i; do echo -n "$i $i "; done; echo

Make executable, and now:

$ ./duplicator.sh dog cat bird whale
dog dog cat cat bird bird whale whale

Alternatively as a shell function, e.g. to be reusable within a script:

duplicator() {
    for i; do echo -n "$i $i "; done; echo
}

which can then be run directly where defined as

duplicator dog cat bird whale

You could use sed:

sed -r 's/(\S+)/\1 \1/g' filename

If you want to save the changes to the file in-place, say:

sed -i -r 's/(\S+)/\1 \1/g' filename

You could also use perl:

perl -M5.10.0 -ne 'say join " ", map{$_, $_} split " ";' filename

(Add the -i option to save the changes to the file in-place.)

Or, as suggested by terdon:

perl -M5.10.0 -ane 'say join " ", map{$_, $_} @F;' filename

Quoting from perlvar:

@F

The array @F contains the fields of each line read in when autosplit mode is turned on. See perlrun for the -a switch. This array is package-specific, and must be declared or given a full package name if not in package main when running under strict 'vars'.


What would this be without an awk/gawk answer:

$ awk '{ for(i=1;i<=NF+1;i+=1/2) { printf("%s ",$i); }}' <<<"dog cat bird whale"
dog dog cat cat bird bird whale whale 

If a terminating newline is important:

$ awk '{ for(i=1;i<=NF+1;i+=1/2) { printf("%s ",$i); }} END{print ""}' <<<"dog cat bird whale"

s="dog cat bird wale"
ss=$( tr ' ' '\n' <<< "$s" | sed p | tr '\n' ' ' )
echo "$ss"
dog dog cat cat bird bird wale wale