Home > other >  Append lines separated by comma while preserving the existing new line
Append lines separated by comma while preserving the existing new line

Time:03-12

Bash script used:

#!/bin/bash
set -xv
IS=$'\n'
list=$(cat exlist_sample | xargs -n1)
for  i in $list; do
    echo "$i" | rev > slist
    echo "$i" >> znamelist

    for x in $(cat slist);do
       echo "this is $x" >> znamelist
       echo $IS >> znamelist
    done
done

Input file used (exlist_sample)

dz-eggg-123
dz-fggg-123
lk-opipo-123
poipo-123-oiu

Current output (final_list)

dz-eggg-123
this is 321-ggge-zd

dz-fggg-123
this is 321-gggf-zd

lk-opipo-123
this is 321-opipo-kl

poipo-123-oiu
this is uio-321-opiop

Expected output:

dz-eggg-123,this is 321-ggge-zd

dz-fggg-123,this is 321-gggf-zd

lk-opipo-123,this is 321-opipo-kl

poipo-123-oiu,this is uio-321-opiop

How to achieve the expected output to make it in csv format in the sciprt while preserving the new line.

CodePudding user response:

Would you please try the following:

#!/bin/bash

while IFS= read -r i; do                        # read the input file line by line
    j=$(rev <<< "$i")                           # reverse the string
    printf "%s,this is %s\n" "$i" "$j"          # print the original string and the reversed one
done < exlist_sample > znamelist

Output:

dz-eggg-123,this is 321-ggge-zd
dz-fggg-123,this is 321-gggf-zd
lk-opipo-123,this is 321-opipo-kl
poipo-123-oiu,this is uio-321-opiop

CodePudding user response:

Here is my version of your script:

#!/bin/bash

inputfile="exlist_sample"
if [[ ! -f "$inputfile" ]]
then
    echo "ERROR: input file $inputfile not found."
    exit 1
fi
outputfile="znamelist"

while IFS= read -r line
do
    reverseline=$(echo "$line"| rev)
    echo -e "$line,this is $reverseline\n"
done < "$inputfile" >"$outputfile"
  • using while with read this way ensures the script will work ok even if there are spaces in lines. It might be overkill a bit for your specific requirement here, but better learn the "safe" way to do it.

  • no need to use files to store the reversed line, you can store it in a variable in each while iteration.

    $ cat znamelist 
    dz-eggg-123,this is 321-ggge-zd
    
    dz-fggg-123,this is 321-gggf-zd
    
    lk-opipo- 123,this is 321 -opipo-kl
    
    poipo-123-oiu,this is uio-321-opiop
    

CodePudding user response:

A one-liner using paste, sed, and rev (though not a POSIX utility) utilities and bash process substitution could be:

paste -d, exlist_sample <(rev exlist_sample | sed 's/^/this is /') > znamelist

CodePudding user response:

With Perl:

perl -ne 'chomp; print $_, ",this is ", scalar reverse, "\n";' exlist_sample

Output:

dz-eggg-123,this is 321-ggge-zd
dz-fggg-123,this is 321-gggf-zd
lk-opipo-123,this is 321-opipo-kl
poipo-123-oiu,this is uio-321-opiop
  • Related