0

So I have a file where each line starts with a number from 1 to 9999 followed by user info like this: inputfile. My question is how I can add the END of line a text string in format: ",C(numberID)" where "numberID" is the number at the start of the line.

I tried this answer from this related question of how to write to the end of line containing a pattern:

sed '/^[0-9],/ s/$/ ,C/' employees2.txt

The output shows that the code works fine since it finds only lines starting with 1 digit number and add to the end of these line a ",C" string. However, what I want is to add a number after that ",C" so I tried this:

sed '/^([0-9],)/ s/$/,C\1' employees2.txt

This causes an error: sed: 1: "/^([0-9],)/ s/$/,C\1": \1 not defined in the RE

My expecting output will be something like this.

Reacher.D
  • 11
  • 3

1 Answers1

1

You can use

sed -E 's/^([0-9]),.*/&,C\1/' employees2.txt  # POSIX ERE
sed 's/^\([0-9]\),.*/&,C\1/' employees2.txt   # POSIX BRE

Details:

  • -E - POSIX ERE syntax enabled
  • ^([0-9]),.* - matches start of string, captures one digit into Group 1, then matches a comma and then any text till end of string (in POSIX BRE, you need to escape the capturing parentheses)
  • &,C\1 - replaces matched line with itself + ,C and the digit from Group 1.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563