Reputation: 167
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
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
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
-
by a newline.*
's.-
.An alternative, using a loop:
sed ':a;s/^\(\**\)[^-*]/\1*/;ta' file
Upvotes: -1
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
Reputation: 88989
With Perl:
perl -pe 's/.(?=.*-)/*/g' file
Output:
*****- 100 ****- 220
Derived from https://stackoverflow.com/a/57458869/3776858
Upvotes: 1
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