Reputation: 55
I have a file content like,
/var/lib/mlocate
/var/lib/dpkg/info/mlocate.conffiles
/var/lib/dpkg/info/mlocate.list
/var/lib/dpkg/info/mlocate.md5sums
/var/lib/dpkg/info/mlocate.postinst
/var/lib/dpkg/info/mlocate.postrm
/var/lib/dpkg/info/mlocate.prerm
In the above file content I want to replace the last slash(/) on every line with space using sed like below
/var/lib mlocate
/var/lib/dpkg/info mlocate.conffiles
/var/lib/dpkg/info mlocate.list
/var/lib/dpkg/info mlocate.md5sums
/var/lib/dpkg/info mlocate.postinst
/var/lib/dpkg/info mlocate.postrm
/var/lib/dpkg/info mlocate.prerm
Please help me in this.
Upvotes: 0
Views: 159
Reputation: 440657
sed 's|\(.*\)/|\1 |' file
sed
's regexes are greedy by default, so .*/
matches everything up to the last /
instance.
sed
uses BREs (basic regular expressions) by default, in which, perhaps surprisingly, (
and )
must be \
-escaped in order to enclose a capture group (capture the enclosed sub-expression separately).
-E
to enable EREs (extended regular expressions), in which case you don't need the escaping of parentheses:sed -E 's|(.*)/|\1 |' file # or -r with GNU Sed / non-macOS BSD Sed
Note how regex delimiter |
was chosen instead of the customary /
; using |
allows unescaped use of /
as a literal to match.
In the replacement part, \1
refers to what the 1st (and only) capture group (\(...\)
) matched, which is everything up to, but not including, the last /
. By following \1
with a literal space you get the desired result.
Upvotes: 1
Reputation: 18411
awk
version: NO reason to do the task with this. But it works :)
awk 'BEGIN{FS=OFS="/"} {$(NF-1)=$(NF-1) " " $NF; NF--} 1' inputfle
/var/lib mlocate
/var/lib/dpkg/info mlocate.conffiles
/var/lib/dpkg/info mlocate.list
/var/lib/dpkg/info mlocate.md5sums
/var/lib/dpkg/info mlocate.postinst
/var/lib/dpkg/info mlocate.postrm
/var/lib/dpkg/info mlocate.prerm
Upvotes: 0