0

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

and

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?

7
  • 1
    How about reading the manual... You'll learn how to reference the matched portion, regardless of what's in the LHS. ;) Commented Jan 22, 2018 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]. Commented Jan 22, 2018 at 0:20
  • "sed s/[0-9]/\0\0/" does the exact same as "sed s/[0-9]/00/" or am I missing something? Commented Jan 22, 2018 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? Commented Jan 22, 2018 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. Commented Jan 22, 2018 at 1:02

1 Answer 1

2

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.

2
  • 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. Commented Jan 22, 2018 at 0:29
  • 2
    A lot of people helped me here answering my questions when I just began. I am just returning this help. Commented Jan 22, 2018 at 0:34

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.