msd_2
msd_2

Reputation: 1187

Replacing multiple lines of text using sed

I have a file input.txt containing the following text

Total users:

    abc
    xyz
    pqrs

The number of users is subject to change but there will be atleast one user all the time. I want to replace the user names with wild card '*' using sed

Total users:

    *   

Is there a way by which I can look for 'Total users:' string and replace everything after that with a *. Some thing like

sed s/Total users: \n[Till EOF]/Toal users: \n*/g

Upvotes: 1

Views: 2065

Answers (3)

Chris Seymour
Chris Seymour

Reputation: 85785

One way:

$ sed '3,$s/\S*$/*/' file
Total users:

    *
    *
    *

This does the substitution s/\S*$/*/ from the third line in the file till the last line 3,$ where the substitution replaces any none whitespace characters till the end of line with a single *. Modified the substitution command as appropriate for your actual file as this will fail if you allow spaces in usernames. A more robust replacement might be:

$ sed -r '3,$s/(\s+).*/\1*/' file
Total users:

    *
    *
    *

This will replace after the initial whitespace with a single *. Use the -i option if you want to store the changes back to the file:

$ sed -ri '3,$s/(\s+).*/\1*/' file

Edit:

To replace all users with a single *:

$ sed -r '3{s/(\s+).*/\1*/;q}' file
Total users:

    *

Although creating this file would have been much quicker than asking a question.

Upvotes: 1

janos
janos

Reputation: 124646

This will do it:

sed -e '/^Total users:/ s/.*/&\n\n    */; q' input.txt

When it finds a line starting with Total users:, it replaces with itself, appends two line breaks and asterisk, and exits without processing any further lines.

If you are using a more limited version of sed where you cannot use ; to separate multiple commands, you can write like this to work around:

sed -e '/^Total users:/ s/.*/&\n\n    */' -e '/^Total users:/ q' input.txt

Which is more verbose, but more portable.

Upvotes: 1

konsolebox
konsolebox

Reputation: 75488

This might be what you need

sed -e "/Total users:/b; s|^\([[:blank:]]*\)[^[:blank:]]\+\(.*\)|\1*\2|" input.txt

Upvotes: 1

Related Questions