Сценарий оболочки для добавления одинарных кавычек и запятых

Вы не упомянули, хотите ли вы фиксированную дату или сейчас (), так что вот один с фиксированной датой:

for i in * ; do echo mv "${i}" "${i%.*}-120917.${i##*.}"; done

А вот и динамическая дата (в соответствии с вашим форматом dmy):

for i in * ; do echo mv "${i}" "${i%.*}-$(date +%d%m%y).${i##*.}"; done

Если результат вас устраивает, удалите echoиз анлайнера.

0
05.02.2020, 01:33
4 ответа

Разделить файл построчно на массив:

# Tell bash that "lines" is an array
declare -a lines

# Read each line of the file
while read line; do
    lines+=("$line")
done <input.txt

Печать результатов:

# Show the first line
echo "${lines[0]}"

# Show all lines
echo "${lines[@]}"

Имейте в виду, что большинство инструментов CLI баз данных позволяют запускать файлы в качестве входных данных. Пример для постгреса :psql -f input.txt

0
28.04.2021, 23:24

Сbash:

mapfile -t a < input.txt      # read input file into array a
printf -v x "'%s'," "${a[@]}" # add single quotes and commas, save result in variable x
printf -v query 'select * from table where columnname in (%s);' "${x:0:-1}" # strip the last comma from x
printf '%s\n' "$query"        # print query

Выход:

select * from table where columnname in ('This is sample','Input file','To execute sql statement');
1
28.04.2021, 23:24

Один вкладыш:

IFS=$'\n'; (read -r L && echo -n "X=('${L//\'/\"}'"; while read -r L; do echo -n ",'${L//\'/\"}'"; done; echo ")";) < input.txt; IFS=' '

(все символы одинарных кавычек 'внутри заменены символом двойных кавычек").

Выход:

X=('This is sample','Input file','To execute sql statement')

Или присвоить переменной:

$ IFS=$'\n'; X=$( (read -r L && echo -n "('${L//\'/\"}'"; while read -r L; do echo -n ",'${L//\'/\"}'"; done; echo ")";) < input.txt); IFS=' '; 
$ echo $X
('This is sample','Input file','To execute sql statement')

Обновлено. Объяснение первого вкладыша:

#
# redefining IFS to read line by line ignoring spaces and tabs
# you can read more about at
# https://unix.stackexchange.com/questions/184863/what-is-the-meaning-of-ifs-n-in-bash-scripting
#
IFS=$'\n';
#
# next actions united inside of round brackets
# to read data from input.txt file
#
# first line from the file read separately,
# because should be printed with opening brackets
#
# between read and echo we use && to make sure
# that data are printed only if reading succeeded
# (that means that the file is not empty and we have reading permissions)
#
# also we print not just "X=($L
# but variable modified in the way to replace ' with "
# more details about it you can find at
# https://devhints.io/bash in Substitution section
# also quotes symbols inside of quoted text are backslash'ed
#
(read -r L && echo -n "X=('${L//\'/\"}'";
#
# now we read lines one by one as long as reading returns data
# (which is until we reach end of file)
# and each time printing:,'LINE-DATA'
# I mean coma and data in single quotes like requested
# where the data are the lines where single quotes replaced
# with double quotes, the same as we did for the first line
while read -r L; do
    echo -n ",'${L//\'/\"}'";
done;
#
# finally we print closing brackets for the data from file
#
# also we close round brackets uniting actions to read data from file
# and specifying file name from where we read data
echo ")";) < input.txt; 
#
# at the end we change IFS back to original.
# actually for 100% accuracy it should be IFS=$' \t\n'
IFS=' '
0
28.04.2021, 23:24

Использование только функций переносимой оболочки:

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

Обратите внимание, что использование циклов оболочки для обработки текста проблематично , но здесь это может иметь смысл, поскольку мы хотим, чтобы содержимое файла заканчивалось в переменной оболочки.

Выход:

$ 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')

Кроме того, вы можете обработать входной файл с помощью такого инструмента, как sed. Этот сценарий добавляет одинарные кавычки по бокам к каждой строке ввода, добавляет все строки в пробел и, как только последняя строка добавлена, помещает содержимое пробела в пространство шаблона, заменяет любой <newline>запятой, добавляет круглые скобки в начало/конец текста и печатает все целиком:

X=$(sed -n '
  s/^/'"'"'/
  s/$/'"'"'/
  H
  1h
  ${
    g
    s/\n/,/g
    s/^/(/
    s/$/)/
    p
  }
  ' input)

Конечно, эти подходы не заботятся об одинарных кавычках, которые могут появиться в ваших строках ввода, что в конечном итоге приведет к неправильному оператору SQL или,по крайней мере, тот, который не даст ожидаемого результата.

0
28.04.2021, 23:24

Теги

Похожие вопросы