BADS
BADS

Reputation: 151

result splitted with a specific character using ksh

I have several input files looking like this and before loop the processing for all the files i would like to get the 1st column in the same line splitted with || .

Input.txt

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

For my try this is my commands :

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

But the problem I got the || in the end of the output file ;

He is the result I'm looking for in one line :

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

Upvotes: 0

Views: 275

Answers (1)

tripleee
tripleee

Reputation: 189377

Probably use Awk instead.

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

If you really wanted to use the shell, you can do pretty much the same thing, but it will typically be both clunkier and slower. Definitely prefer the Awk version for any real system.

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

Notice the absence of a 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.

If you want a space after the delimiter, set it to "|| " instead of just "||". Your example is not entirely consistent (or maybe the markup here hides some of your formatting).

Upvotes: 2

Related Questions