15

I am facing some problem regarding my bash script.

Below is my bash code :

#!/bin/bash

cd /root/Msgs/TESTNEW/new

file=myfile.txt

var1=$(awk '(NR==30){print $2}' $file)
var2=$(awk 'NR>=38 && NR<=39' $file)
var3=${var2// /+}

curl "http://<server_ip>/power_sms/send_sms.php?username=<user>&password=<pass>phoneno=$var1&text=$var3"

This scripts purposed is for reading in a range of line in particular file(for ex:myfile.txt).Then it will put the content of the file into some variable(var1,var2). After that,the variable will be called into the curl functions.

The problems start when the content of the file have spacing in every new line.This making the curl not functioning as it do not accept white space character.I have manage to replace the spacing into plus symbols.But whenever there is new line,it will have spacing rather than having plus symbol.

Some of the output is as below:

hi+there.hopefully+you+can+get+this+email+which+are being+send+as+sms.

Can someone help me?Thanks.

user119720
  • 380
  • 3
  • 6
  • 19

5 Answers5

19

If you are using linux then this will substitute newlines to +

awk '{printf "%s+",$0} END {print ""}'

or with sed

sed ':a;N;$!ba;s/\n/+/g'

Sirch
  • 5,697
  • 4
  • 19
  • 36
  • 1
    +1 for answering the real question – Petr Jun 13 '16 at 12:39
  • 2
    NOTE: on OS X this won't work as sed is to an older spec. Use `gsed` if you need the full GNU sed functionality. So, `brew install gsed` to install it via Homebrew. – cwingrav May 11 '18 at 19:33
19
awk NF=NF RS= OFS=+

Result

hi+there.hopefully+you+can+get+this+email+which+are+being+send+as+sms.
Zombo
  • 1
  • 1
  • 16
  • 18
11

EDIT: For the solution with awk, you are looking for this:

awk 'BEGIN {RS=""}{gsub(/\n/,"",$0); print $0}' myfile.txt

Another method to strip all newlines from your file:

tr -d "\n"

An example:

tr -d "\n" < myfile.txt > myfilewithoutnewlines.txt
Silviu
  • 637
  • 8
  • 15
4

You are doing this the wrong way. You need to URL-encode your text to get a truly universal solution:

When you do this and use a text like this:

This is 
a test 
text

you end up with this: This+is+%0d%0aa+test+%0d%0atext.

You can use curl to do this:

curl -G -d username=<user> -d password=<pass> -d phoneno=$var1 \
       --data-urlencode text@myfile.txt \
       http://<server_ip>/power_sms/send_sms.php

For more info, see man curl.

Sven
  • 97,248
  • 13
  • 177
  • 225
1

I just wanted to point out in @Sirch sed code you can replace the aforementioned, "+" with any other separator. I hope this helps a few beginners!

example

sed ':a;N;$!ba;s/\n/   /g' #puts 3 spaces between the result
MickyG
  • 11
  • 1