使用 ksh 将结果拆分为特定字符

result splitted with a specific character using ksh

我有几个看起来像这样的输入文件,在对所有文件进行循环处理之前,我希望在同一行中的第一列用 || 分隔.

Input.txt

aa      ,DEC   
bb      ,CHAR       
cc      ,CHAR      
dd      ,DEC    
ee      ,DEC   
ff      ,CHAR     
gg      ,DEC   

为了我的尝试,这是我的命令:

cat | while read line
do
cle=`echo $line|cut -d"," -f1`
        for elem in $cle 
        do
            echo -n "$elem||"
        done
    fi
done 

但是我得到的问题是||在输出文件的末尾 ;

他是我在一行中寻找的结果:

aa || bb || cc || dd || ee || ff || gg 

可能改用 Awk。

awk -F ',' '{ printf "%s%s", sep, ; sep = "||"; } END { printf "\n" }' ""

如果您真的想使用 shell,您可以做几乎相同的事情,但通常会更笨重和更慢。绝对喜欢任何真实系统的 Awk 版本。

sep=''
while IFS=',' read -r cle _; do
    printf "%s%s" "$sep" "$cle"
    sep="||"
done <""
printf "\n"

注意缺少 useless cat and how the read command itself is perfectly able to split on whatever IFS is set to. (Your example looks like maybe you want to split on whitespace instead, which is the default behavior of both Awk and the shell. Drop the -F ',' or remove the IFS=',', respectively.) You obviously don't need a for loop to iterate over a single value, either. And always quote your variables.

如果您想要在分隔符后添加 space,请将其设置为 "|| " 而不是 "||"。您的示例并不完全一致(或者此处的标记可能隐藏了您的某些格式)。