Using portable shell features only:
oIFS=$IFS # Store the IFS for later;
IFS= # Empty the IFS, to ensure blanks at the
# beginning/end of lines are preserved
while read -r line; do # Read the file line by line in a loop,
set -- "$@" "'""$line""'" # adding each line to the array of positional
done < input # parameters, flanked by single quotes
IFS=, # Set "," as the first character of IFS, which
# is used to separate elements of the array
# of positional parameters when expanded as
# "$*" (within double quotes)
X=\("$*"\) # Add parentheses while assigning to "X"
IFS=$oIFS # Restore the IFS - to avoid polluting later
# commands' environment
Note that using shell loops for processing text is problematic, but it may make sense here because we want the file content to end up in a shell variable.
The output:
$ printf "%s %s\n" 'select * from table where columnname in' "$X"
select * from table where columnname in ('This is sample','Input file','To execute sql statement')
Alternatively, you may process your input file with a tool like sed
. This script adds flanking single quotes to each input line, appends all the lines to the hold space and, once the last line has been appended, puts the content of the hold space into the pattern space, replaces any <newline>
with a comma, adds parentheses at the beginning/end of the text and prints the whole thing:
X=$(sed -n '
s/^/'"'"'/
s/$/'"'"'/
H
1h
${
g
s/\n/,/g
s/^/(/
s/$/)/
p
}
' input)
Of course, these approaches don't take care of single quotes that may appear in your input lines, which will eventually make for a broken SQL statement or, at least, one that won't yield the expected result.
also, how the above variable can be given to sql query as input ??, Im afraid it cannot be taken..
– Jman91 Feb 04 '20 at 19:21This is sample,Input file,To execute sql statement
But I need like below'This is sample','Input file','To execute sql statement'
– Jman91 Feb 04 '20 at 19:36