11

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!

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

5 Answers5

26

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
Kusalananda
  • 333,661
6
sed --in-place 's/ /-/g' /path/to/file
DopeGhoti
  • 76,081
3

with perl:

perl -ne 's/ /-/g;print ' FILE 
Baba
  • 3,279
  • Bit weird to use -n to not 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
  • @StéphaneChazelas The answer is from 7 years ago. I have no idea about my answer; Your comment is definitely correct – Baba Dec 23 '22 at 17:29
2

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
0

I like to use replace.

replace " " "-" </path/to/file 
  • 1
    I like to have my scripts be portable... ;-) – Kusalananda Jun 16 '16 at 20:42
  • In this case i prefer to use shell script for anything, using only shell commands so it can run in various kinds of jail shell. But the user wont like to use the while loop, as they say. – Luciano Andress Martini Jun 16 '16 at 20:44
  • So 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
  • No isnt a shell script, im not trying to help with a shell script because the user wont to use shell script built-in command, but external tools like sed or tr, or replace! Its a external program that i think its very faster. I am giving +1 for you because tr is a very common tool in a lot of unix environments. But i personally prefer to use pure shell built-in commands, even if the unix clans think it is a bad practice. – Luciano Andress Martini Jun 16 '16 at 20:48