Maqruis1
Maqruis1

Reputation: 167

sed: replace characters before '-'

I have a text file like so:

every-    100
atmo-   220

I wish to replace character before - with *. So the expected output should be

*****-    100
****-   220

How would I do that using sed?
I have tried using s/[a-z]*-/*/g but it does not work and replaces before and including the - with a single *

How do I fix this?

Upvotes: 0

Views: 107

Answers (5)

Jon
Jon

Reputation: 3671

Another way of coding it in sed:

$ sed ':loop ; /[^*]-/s/[^*]/*/ ; t loop' <<END
every-    100
atmo-   220
END
*****-    100
****-   220

And an alternative coding in Perl:

perl -pe 's/[^*]/*/ while /[^*]-/'

Upvotes: 0

potong
potong

Reputation: 58578

This might work for you (GNU sed):

sed 's/-/\n/;h;s/[^\n]/*/g;G;s/\n.*\n/-/' file

This uses a newline as a delimiter and a copy to achieve the required result

  • Replace the - by a newline.
  • Copy the line.
  • Replace everything except the newline by *'s.
  • Append the copy.
  • Replace everything between the newlines by a single -.

An alternative, using a loop:

sed ':a;s/^\(\**\)[^-*]/\1*/;ta' file

Upvotes: -1

Cyrus
Cyrus

Reputation: 88989

With GNU awk. Use - as input and output field separator and replace in first column everything with *.

gawk 'BEGIN{FS=OFS="-"} gsub(/./,"*",$1)' file

Output:

*****-    100
****-   220

Upvotes: 1

Cyrus
Cyrus

Reputation: 88989

With Perl:

perl -pe 's/.(?=.*-)/*/g' file

Output:

*****-    100
****-   220

Derived from https://stackoverflow.com/a/57458869/3776858

Upvotes: 1

oguz ismail
oguz ismail

Reputation: 50815

Implement a loop using labels and branching:

$ sed ':1; s/^\(\**\)[a-z]/\1*/; t1' <<EOF
every-    100
atmo-   220
EOF
*****-    100
****-   220

Upvotes: 2

Related Questions