8

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.

13

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'

| improve this answer | |
  • 1
    +1 for answering the real question – Petr Jun 13 '16 at 12:39
  • 1
    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
13
awk NF=NF RS= OFS=+

Result

hi+there.hopefully+you+can+get+this+email+which+are+being+send+as+sms.
| improve this answer | |
  • 2
    Why isn't this at the top? – dessert Nov 15 '17 at 20:33
8

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
| improve this answer | |
  • Or just awk '{printf "%s" $0}' <file. – dessert Jan 30 '18 at 12:55
3

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.

| improve this answer | |
0

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
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.