30

I have a variable whose value is found using sql query.

I want to remove the new line character from that variable since I want to concatenate this variable with the other. Below is the code:

dt=`sqlplus -s user/pwd@servicename <<EOF
set feedback off;
set head off;
select  replace(to_char((sysdate-7),'YYYYMonDD')||'_'||to_char((sysdate-1),'YYYYMonDD'),chr(10), '') from dual;
exit;
EOF`

echo "test $dt"

4 Answers 4

51

If you are using bash, you can use Parameter Expansion:

dt=${dt//$'\n'/} # Remove all newlines.
dt=${dt%$'\n'}   # Remove a trailing newline.

The following should work in /bin/sh as well:

dt="${dt%
}"                # Remove a trailing newline.
8
  • 5
    Just FYI, when you're using ${var//a/} you don't need to use last /, ${var//a} will do exactly the same. Commented Nov 29, 2012 at 13:28
  • Thank you all.Below thing worked dt=${dt//$'\n'/} # Remove all newlines. Commented Nov 29, 2012 at 13:58
  • 2
    For those curious in the full syntax, here is a link to the bash documentation: gnu.org/software/bash/manual/html_node/… Commented Jun 26, 2019 at 17:40
  • 1
    dt=${dt//[$'\n\r']/} if you need to remove Carriage Returns as well Commented Mar 8, 2022 at 11:30
  • 1
    @Mr.Míng: ${dt%%$'\n'} still removes a single newline as there's no wildcard. You can use shopt -s extglob ; s=${s%%*($'\n')} though. Commented Nov 23, 2022 at 9:18
29

Sounds like you need "tr", something like:

 echo ${dt} | tr -d '\n'

man tr for detail, as usual

1
  • 1
    simple and readable +1 Commented Jul 15, 2021 at 9:16
3

This work on Linux (bash):

dt="$(echo "$dt"|tr -d '\n')"

On Linux, or other systems with GNU's date utility, this also works to get that value for dt: (without involving Oracle...)

dt="$(date -d 'yesterday' +%Y%b%d)_$(date -d '7 days ago' +%Y%b%d)"
1
  • +1 for avoiding sqlplus. If you're on a system without GNU date but you have Tcl: echo 'puts [clock format [clock scan "-1 week"] -format %Y%b%d]_[clock format [clock scan yesterday] -format %Y%b%d]' | tclsh Commented Nov 29, 2012 at 14:55
0

from the Oracle sqlplus manual

SET PAGES[IZE] {14 | n} Sets the number of lines on each page of output. You can set PAGESIZE to zero to suppress all headings, page breaks, titles, the initial blank line, and other formatting information.

so add a set pagesize 0 to your script to avoid a heading blank line.

for most of my scripts I use the settings in the following code piece of code:

dt=`sqlplus -s user/pwd@servicename < < EOF
set feedback off
set pagesize 0
set trimout on
set trimspool on
set linesize 300
set echo off
set verify off

select  replace(to_char((sysdate-7),'YYYYMonDD')||'_'
||to_char((sysdate-1),'YYYYMonDD'),chr(10), '') from dual;
exit;
EOF`

echo "test $dt$dt"

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.