adding line number to *end* of records in file

Given a file like this:

abc
def
ghi

I need to get to

somestandardtext abc1 morestandardtext
somestandardtext def2 morestandardtext
somestandardtext ghi3 morestandardtext

Notice that in addition to the standard text there is the line number added in as well. What I conceived is one sed command to add the 'somestandardtext' (easy to do), then a second one to add the line number, then a third to add 'morestandardtext'.

Lot's of examples on about adding the number to the beginning, but I can't seem to work out how to add it to the end

As always, if there is a better approach, I'm all eyes .. perhaps referencing an sed script file instead of inline commands?

What about using awk in this case?

awk '{ print "somestandardtext", $0 NR, "morestandardtext" }' inputfile >outputfile

---------- Post updated at 21:33 ---------- Previous update was at 21:25 ----------

And if you want to use sed, try

sed -n 'p;=' inputfile | sed 'N;s/\n//; s/^/somestandardtext /; s/$/ morestandardtext/'

Both very close.

The awk solution gives me everything I need, except it is inserting an unwanted space where we break between quoted text and field references.

the sed solution eliminates the space problem (as well as not having to escape a bunch of quotes in the standard text), but my example was a bit more simple than reality, and I'm not bridging the gap.

Let's say I start with file myfile.txt

abc
def
ghi

I need to get
SOMECANNEDTEXTabcSOMEMORETEXT1STILLMORETEXT
SOMECANNEDTEXTdefSOMEMORETEXT2STILLMORETEXT
SOMECANNEDTEXTghiSOMEMORETEXT3STILLMORETEXT

Note that the line number is appended at the end of SOMEMORETEXT

I appreciate the help. I'm learning a lot here but still having trouble getting my head wrapped around some of it.

To get rid of the blank, replace a comma with a blank in the awk-command. NR is a special variable which holds the current line number, as you may have guessed.

awk '{ print "SOMECANNEDTEXT" $0 "SOMEMORETEXT" NR "STILLMORETEXT" }' inputfile >outputfile

With sed you have to mix up the components a little bit:

sed -n 's/^/SMOECANNEDTEXT/; s/$/SOMEMORETEXT/; p; =' inputfile| sed 'N; s/\n//; s/$/STILLMORETEXT/'

Hope, this helps.

1 Like

Both achieve exactly what I need. thank you so much.