修改bash中的字符串以包含换行符?

时间:2016-09-07 17:26:57

标签: python bash google-api

我正在使用bash脚本调用google-api的upload_video.py(https://developers.google.com/youtube/v3/guides/uploading_a_video

我有一个名为output.mp4的mp4,我想上传。

问题是我不能让我的阵列按照我想要的方式工作。

这个新行字符是"必需"因为我对python脚本的参数包含空格。

以下是我的bash脚本的简化版本:

# Operator may change these
hold=100
location="Foo, Montana "
declare -a file_array=("unique_ID_0" "unique_ID_1")

upload_file=upload_file.txt
upload_movie=output.mp4

# Hit enter at end b/c \n not recognized
upload_title=$location' - '${file_array[0]}' - Hold '$hold' Sweeps 
'
upload_description='The spectrum recording was made in at '$location'.
'
# Overwrite with 1st call > else apppend >>
echo "$upload_title" > $upload_file
echo "$upload_description" >> $upload_file

# Load each line of text file into array
IFS=$'\n'
cmd_google=$(<$upload_file) 
unset IFS

nn=1
for i in "${cmd_google[@]}"
do
    echo "$i"
    # Delete last character: \n 
    #i=${i[-nn]%?}
    #i=${i: : -nn}
    #i=${i::${#i}-nn}
    i=${i%?}
    #i=${i#"\n"}
    #i=${i%"\n"}
    echo "$i"
done

python upload_video.py --file=$upload_movie --title="${cmd_google[0]}" --description="${cmd_google[1]}"

起初我尝试删除新行字符,但是看起来输入或\ n不能正常工作我想要的,每行不是分开的。它将标题和描述写为一行。

如何修改bash脚本以识别换行符?

2 个答案:

答案 0 :(得分:0)

这比制作它简单得多。

# Operator may change these
hold=100
location="Foo, Montana"
declare -a file_array=("unique_ID_0" "unique_ID_1")

upload_file=upload_file.txt
upload_movie=output.mp4

upload_title="$location - ${file_array[0]} - Hold $hold Sweeps"
upload_description="The spectrum recording was made in at $location."

cat <<EOF > "$upload_file"
$upload_title
$upload_description
EOF

# ...

readarray -t cmd_google < "$upload_file"

python upload_video.py --file="$upload_movie" --title="${cmd_google[0]}" --description="${cmd_google[1]}"

我怀疑readarray命令是你真正想要的,因为上面的大部分代码只是创建一个我认为你已经收到的文件。

答案 1 :(得分:0)

我在chepner的回答中得到了帮助。我的问题隐藏了这样一个事实:我想在视频的描述中写下新的行字符。

不是在bash脚本中添加换行符,而是使用包含正确格式化脚本的文本文件并将其读入,然后将其与运行时特定变量连接起来要容易得多。

在我的情况下,正确格式化的文本称为description.txt:

Here is a snip of my description.txt which contains newline characters

这是我脚本的最终版本:

# Operator may change these
hold=100
location="Foo, Montana"
declare -a file_array=("unique_ID_0" "unique_ID_1")

upload_title="$location - ${file_array[0]} - Hold $hold Sweeps"
upload_description="The spectrum recording was made in at $location. "
# Read in script which contains newline
temp=$(<description.txt)
# Concatenate them
upload_description="$upload_description$temp"

upload_movie=output.mp4

python upload_video.py --file="$upload_movie" --title="$upload_title" --description="$upload_description"