Linux removes spaces after a character in a string

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

My number = 1234; # This is a random number

Can I use sed or something else to replace all spaces after '#' with '+' so that the result looks like this:

My number = 1234; # This + this + a + random + number

+6
source share
5 answers

One way: awk :

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

Result:

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

EDIT:

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

 awk -F# 'OFS=FS { for (i=2; i <= NF; i++) gsub(" ", "+", $i); print }' file.txt 
+3
source

You can do it in a clean 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 in variables for later use is left as an exercise for the reader. :-)

Note that this also holds a few # characters per 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 prefer to create a variable over 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 can 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 fun, here's a short awk solution:

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

Pay attention to the final ORS. I do not know if the final record separator can be avoided. I suppose you could get rid of this by plotting the line above through head -1 , assuming that you are dealing with only one line of input.

+3
source

Not terribly effective, but:

 perl -pe '1 while (s/(.*#[^ ]*) /\1+/);' 
+2
source

This may work for you (GNU sed):

 echo 'My Number is = 1234; #This is a random number' | sed 's/#/\n&/;h;s/.*\n//;y/ /+/;H;g;s/\n.*\n//' My Number is = 1234; #This+is+a+random+number 
+2
source

Here is another perl single line:

 echo 'My Number is = 1234; #This is a random number' \ | perl -F\# -lane 'join "#", @F[1,-1]; s/ /+/g; print $F[1], "#", $_' 
  • -F indicates how to split the string into an @F array.
  • -an wraps stdin with:
 while (<>) { @F = split('#'); # code from -e goes here } 
+1
source

Source: https://habr.com/ru/post/920846/


All Articles