Alfonso Ventanova Alfonso Ventanova - 5 months ago 7
Bash Question

Replace some but not all spaces in text file (shell/bash)

Let's say that I have a file (example.txt) with the next structure:

NAAME 111 2222 333
NAMME 111 22 333
NNA ME 444 555 2
NNAAME 1 5 8
N MEEE 44 66 111


I would like to replace the spaces between the numbers with a separator, like
|
or
,
but not affecting the name.

One option I was thinking is to change the space in the name and put a "low bar", then remove all the spaces in the file and write "|" and after change again the "_" in the name for a space.

Any idea how to do that in shell? Or maybe a better option?

The expect output would be this

NAAME|111|2222|333
NAMME|111|22|333
NNA ME|444|555|2
NNAAME|1|5|8
N MEEE|44|66|111


Thank you very much!

Answer

you can use a sed expression to do that:

sed -i 's/\([[:digit:]]\)\ \([[:digit:]]\)/\1|\2/g' file.txt

output:

NAME1|111|2222|333
NAME2|111|22|333
NA ME3|444|555|2
NAME4|1 5|8
N ME5|44|66|111

explanation of the sed command:

  • -i : in-place: modify file.txt
  • [[:digit:]] : as you might think: matches a digit
  • \(<patter>\) : enclosing something between escaped brackets \( and \) makes them a pattern that can be referenced. Since I used this twice; in the second part of the sed command; I can use \1 and \2 to refer to these two patterns.