Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux delete spaces after a character in a line

Tags:

linux

replace

sed

In Linux, if I have a file with entries like:

My Number is = 1234; #This is a random number

Can I use sed or anything else to replace all spaces after '#' with '+', so that the output looks like:

My Number is = 1234; #This+is+a+random+number

like image 765
user1536435 Avatar asked Jul 19 '12 00:07

user1536435


People also ask

How do I remove spaces from a char string?

Use replace () function to replace all the space characters with a blank. The resulting string will not have any spaces in-between them.

How do I remove spaces from a line in Unix?

The command gsub(/ /,"") removes blanks from those lines.


2 Answers

One way using awk:

awk -F# 'OFS=FS { gsub(" ", "+", $2) }1' file.txt

Result:

My Number is = 1234; #This+is+a+random+number

EDIT:

After reading comments below, if your file contains multiple #, you can try this:

awk -F# 'OFS=FS { for (i=2; i <= NF; i++) gsub(" ", "+", $i); print }' file.txt
like image 161
Steve Avatar answered Nov 14 '22 22:11

Steve


You can do this in pure shell...

$ foo="My Number is = 1234; #This is a random number"
$ echo -n "${foo%%#*}#"; echo "${foo#*#}" | tr ' ' '+'
My Number is = 1234; #This+is+a+random+number
$ 

Capturing this data to variables for further use is left as an exercise for the reader. :-)

Note that this also withstands multiple # characters on the line:

$ foo="My Number is = 1234; #This is a # random number"
$ echo -n "${foo%%#*}#"; echo "${foo#*#}" | tr ' ' '+'
My Number is = 1234; #This+is+a+#+random+number
$ 

Or if you'd prefer to create a variable rather than pipe through tr:

$ echo -n "${foo%%#*}#"; bar="${foo#*#}"; echo "${bar// /+}"
My Number is = 1234; #This+is+a+#+random+number

And finally, if you don't mind subshells with pipes, you could do this:

$ bar=$(echo -n "$foo" | tr '#' '\n' | sed -ne '2,$s/ /+/g;p' | tr '\n' '#')
$ echo "$bar"
My Number is = 1234; #This+is+a+#+random+number
$

And for the fun of it, here's a short awk solution:

$ echo $foo | awk -vRS=# -vORS=# 'NR>1 {gsub(/ /,"+")} 1'
My Number is = 1234; #This+is+a+#+random+number
#$ 

Note the trailing ORS. I don't know if it's possible to avoid a final record separator. I suppose you could get rid of that by piping the line above through head -1, assuming you're only dealing with the one line of input data.

like image 22
ghoti Avatar answered Nov 14 '22 21:11

ghoti