删除两个特定字符串之间的换行符

时间:2015-04-09 07:51:59

标签: shell unix scripting

我正在使用Unix Shell。如何删除两个特定字符串之间的换行符。

例如,输入为:

CASE when a in ('abcd','bdcdf') then
  Shng,
END as xyz

输出应为:

CASE when a in ('abcd','bdcdf') then Shng END as xyz, 

1 个答案:

答案 0 :(得分:0)

解析行的文件行,并在看到CASE或END时记住 下面的代码使用if语句的短语法和使用-n参数抑制\ n的回声。

incase=0
cat x.sql | while read -r line; do
   [[ ${line} = CASE* ]] && incase=1;
   [[ ${line} = END* ]] && incase=0
   [[ ${incase} = 0 ]] && echo "${line}"
   [[ ${incase} = 1 ]] && echo -n "${line} "                                               
done

编辑:
当你有嵌套的CASE(如CASE ... CASE ... END ... END)和所有 CASE从不同的行开始,您可以计算嵌套的深度。

incase=0
cat x.sql | while read -r line; do
   [[ ${line} = CASE* ]] && (( incase = incase + 1)) ;
   [[ ${line} = END* ]] && (( incase = incase - 1)) 
   [[ ${incase} = 0 ]] && echo "${line}"
   [[ ${incase} > 0 ]] && echo -n "${line} "                                               
done
# You might want an extra echo here so your last line will finish with a \n
echo

编辑2:通常你可以避免使用猫(寻找UUOC)。这里的代码更好

incase=0
cat x.sql | while read -r line; do
   [[ ${line} = CASE* ]] && incase=1;
   [[ ${line} = END* ]] && incase=0
   [[ ${incase} = 0 ]] && echo "${line}"
   [[ ${incase} = 1 ]] && echo -n "${line} "                                               
done

编辑:
当你有嵌套的CASE(如CASE ... CASE ... END ... END)和所有 CASE从不同的行开始,您可以计算嵌套的深度。

incase=0
while read -r line; do
   [[ ${line} = CASE* ]] && (( incase = incase + 1)) ;
   [[ ${line} = END* ]] && (( incase = incase - 1)) 
   [[ ${incase} = 0 ]] && echo "${line}"
   [[ ${incase} > 0 ]] && echo -n "${line} "                                               
done < x.sql
# You might want an extra echo here so your last line will finish with a \n
echo