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.

1

3 Answers 3

1

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

awk '{print $1,$1 ".doe"}' names.txt
3
  • 1
    Thank you Romeo. I was stuck on using sed that I completely neglected to explore awk. This worked beautifully! Apr 20 at 5:48
  • Romeo, if someone puts awk in a for loop, would you rather recommend to use sed instead or explain what is wrong with that approach?
    – Philippos
    Apr 20 at 6:30
  • @Philippos, this depend of particular case. There no only one way to do the things. Apr 20 at 6:33
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.

0
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
1
  • 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 at 8:06

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.