1) sed command which puts two of the first 'w' on each line. E.g "hewor" = "hewwor".


2) sed command which puts two of the first digit on each line E.g "hew0r" = "hew00r"

For first one I got

$ sed s/w/ww/ 

for the second one I don't understand how to replicate the same digit for example I got

$ sed s/[0-9]/00/

would work but it would have to be zero each time. How do I get the same digit?

  • 1
    How about reading the manual... You'll learn how to reference the matched portion, regardless of what's in the LHS. ;) – don_crissti Jan 22 '18 at 0:13
  • My bad, I meant $sed s/[0-9]/00/ as you can see, it has to be zero. I'm looking for a way for the digit to be the one found in the [0-9]. – Tinler Jan 22 '18 at 0:20
  • "sed s/[0-9]/\0\0/" does the exact same as "sed s/[0-9]/00/" or am I missing something? – Tinler Jan 22 '18 at 0:42
  • Yes. It becomes hew4r -> hew00r. I want hew44r. Also, why should I use that instead of "sed s/[0-9]/00/"? For this and the first example? – Tinler Jan 22 '18 at 0:51
  • OK. in gnu sed using \0 refers to the previously matched regex. In bsd sed this is done using &. So in your case since \0 does not work, you can use sed 's/[0-9]/&&/'. Actuall using & will work even in gnu sed. – George Vasiliou Jan 22 '18 at 1:02

You need to use the sed's feature, called groups (may be not the best reference, try to search for other tutorials). In you case the solution is

sed 's/\([0-9]\)/\1\1/' input_file.txt

the regexp for the first group \([0-9]\) will match any digit, and the part \1\1 says to replace the first group with itself repeated twice.

| improve this answer | |
  • 1
    I don't think the purpose of this assignment is to teach them how to use groups. The link is good though, it has the answer. – don_crissti Jan 22 '18 at 0:29
  • 2
    A lot of people helped me here answering my questions when I just began. I am just returning this help. – John Smith Jan 22 '18 at 0:34

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.