Given a file with multiple lines, I want to change every space to dash.
I did like that:
#!/bin/bash
while read line; do
echo "${line// /-}"
done
This works just fine, but I need a better method!
Given a file with multiple lines, I want to change every space to dash.
I did like that:
#!/bin/bash
while read line; do
echo "${line// /-}"
done
This works just fine, but I need a better method!
The standard tr
utility does exactly this:
tr ' ' '-' <filename.old >filename.new
You can use a tool like sponge
to do in-place editing (hides the fact that a temporary file is being used):
tr ' ' '-' <filename | sponge filename
tr ' ' - < filename 1<> filename
– Stéphane Chazelas
Dec 23 '22 at 17:23
with perl:
perl -ne 's/ /-/g;print ' FILE
-n
to n
ot print
and then call print
by hand afterwards. Why not just perl -pe 's/ /-/g' FILE
?
– Stéphane Chazelas
Dec 23 '22 at 17:24
Use -i
to have it write the changes to the file or the -e
to have it just write the changes to stdout without modifying the file.
sed -i 's/ /-/g' filename
sed -e 's/ /-/g' filename
I like to use replace.
replace " " "-" </path/to/file
replace
is a script that you wrote? I've never seen it before. It certainly isn't a standard Unix utility and it's not available on the machines I'm using. Oh, I found it! It's a Linux thingy? Cute. ;-)
– Kusalananda
Jun 16 '16 at 20:47