lkotlus
lkotlus

Reputation: 31

How do I delete part of the lines of a file with sed?

So I need to format a file that has the sudo group on the line of a file with bash. It looks like this by default:

linenumber:sudo:x:user1,user2,etc...

So I want to use sed to make it look like this:

user1,
user2,
etc...

(I don't need the extra space in between, the formatting just made it so if there wasn't an extra space it would look like this: user1,user2,etc...)

So to do this I need to find the last : in the file and then format it the correct way. I don't need to use sed, but I assume it is the answer. Thanks in advance for answers!

Upvotes: 1

Views: 480

Answers (3)

tripleee
tripleee

Reputation: 189357

With Bash builtins, getting everything after the last colon from a string you already have in a variable,

string=${string##*:}
echo "${string//,/$'\n'}"

Upvotes: 1

potong
potong

Reputation: 58381

This might work for you (GNU sed):

sed '/sudo/{s/.*://;s/,/&\n/g}' file

For any line that contains sudo, remove up to and including the last : in the line and then replace each , by a , followed by a newline.

Upvotes: 2

Justin
Justin

Reputation: 23

Use cut, with : as the deliminator. Searching for position 4, like this: 1:2:3:4

cut -d ':' -f 4

To format it to the example you wanted, combine cut with tr to replace comma with a new line.

cut -d ':' -f 4 | tr ',' '\n'

Upvotes: 0

Related Questions