Reputation: 23
I'm looking to replace a space
that always comes after a number with a |
in the middle of a pattern. There are also similar patterns later in the line sometimes that I do not wish to replace (see first/second lines in the examples).
example:
12315 asdfea 1 1ffesa
45456 asefasef 1 era
12 asfase
4 4aefs
what I need:
12315|asdfea 1 1ffesa
45456|asefasef 1 era
12|asfase
4|4aefs
I have tried this:
sed 's/\([0-9][ ][a-zA-Z]\)/|/g' file.txt
However this deletes the pattern such that it looks like this:
|sdfea 1 1ffesa
|sefasef 1 era
|sfase
|4aefs
Which is not what I need.
Upvotes: 2
Views: 284
Reputation: 23667
For given sample input/output,
$ sed 's/ /|/' file.txt
12315|asdfea 1 1ffesa
45456|asefasef 1 era
12|asfase
4|4aefs
By default, only first match will be replaced. g
modifier will replace all matches
To replace first matched space between a digit and alphabet (matching depends on locale too)
$ sed 's/\([0-9]\) \([a-zA-Z]\)/\1|\2/' file.txt
12315|asdfea 1 1ffesa
45456|asefasef 1 era
12|asfase
4 4aefs
This uses capture group and backreferences. Note that last line is not modified
Upvotes: 1