我一直在为此而努力。
我想在bash中按字符循环多行字符串,但是丢失了所有换行符。当我没有发现任何明显错误时,我做的第一件事就是对它运行shellcheck
,这对程序来说似乎很好。
script.sh :
#!/usr/bin/env bash
transform_single() {
if [[ $# -ne 1 ]]; then
echo 'Error: illegal number of args' 1>&2
fi
equation=''
delim0=0
delim="$1"
while IFS= read -rn1 c; do
if [[ $delim0 -eq 0 ]] && [[ "$c" == "$delim" ]]; then
delim0=1
equation=''
elif [[ $delim0 -ne 0 ]] && [[ "$c" == "$delim" ]]; then
delim0=0
echo -n "$equation" | texmath
elif [[ $delim0 -ne 0 ]]; then
equation="$equation$c"
else
echo -n "$c"
fi
done
}
transform_single '$'
input.txt中:
<newlines>
<newlines>
# Hello world!
<newlines>
This is a test string.
<newlines>
调用:
bash script.sh < input.txt
输出:
# Hello world!This is a test string.
例外输出:
与输入文件相同。
答案 0 :(得分:0)
工作脚本
#!/bin/bash
transform_single() {
if (($# != 1)); then echo 'Error: illegal number of args' 1>&2; fi
equation=''
delim0=0
delim="$1"
while IFS= read -r -d $'\0' -n 1 c; do
if ((delim0 == 0)) && [[ "$c" == "$delim" ]]; then
delim0=1
equation=''
elif ((delim0 != 0)) && [[ "$c" == "$delim" ]]; then
delim0=0
echo -n "$equation" | texmath
elif ((delim0 != 0)); then
equation="$equation$c"
else
echo -n "$c"
fi
done
}
transform_single '$'
问题是您必须设置分隔符以读取空字符,以保留换行符。