0

I know the title sounds a little confusing, but hopefully my example will clarify my issue.

So I have a file with a list of names (names.txt), for example:

john
david
richard

I'm trying to use a loop to get to the following result:

john john.doe
david david.doe
richard richard.doe

Not sure if using sed is the right command or approach, but here's what I've tried:

for i in $(cat names.txt); do sed "s/$/ $i.doe/" names.txt; done

This 'sort of' works, but spits out an iterative list like this instead:

john john.doe
david john.doe
richard john.doe
john david.doe
david david.doe
richard david.doe
john richard.doe
david richard.doe
richard richard.doe

I've also tried a while IFS= read -r loop as well with similar results. Can't seem to just deal with each line without resulting above.

I'm likely completely off the mark here, but hoping someone can help here.

Apologies in advance. I've used sed before but for rather easier tasks.

3 Answers3

1

One possible way is to use awk. Command like this can do the work:

awk '{print $1,$1 ".doe"}' names.txt
Romeo Ninov
  • 17,484
1

You midunderstand sed. You don't need to loop over sed, it loops over all lines anyhow. Simply do the replacement

sed 's/.*/& &.doe/' names.txt

.* matches the whole line, and & in the replacement inserts the whole match.

You don't need to switch the tool, just use the tool like it is meant to be.

Philippos
  • 13,453
0

Done through sed

sed -r -e  "s/\s+//g" -e "s/.*/& &.doe/g" file1

output

john john.doe
david david.doe
richard richard.doe
  • 3
    Please mention that your code will work with GNU sed only. And while the first part is superfluous for a name file without spaces, an explanation what was wrong with the OP's original attempt would not have been superfluous. – Philippos Apr 20 '22 at 08:06