Search code examples
bashshellawkscriptingtext-processing

Append lines separated by comma while preserving the existing new line


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.


Solution

  • 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