Search code examples
carriage-return

Why does appending text to the end of each line replaces the first characters instead?


I searched everywhere but I haven't seen anyone have the same issue, yet alone a solution to this. I am trying to add text at the end of each line like so:

"Name1";"2913"
"Name2";"2914"

into:

"Name1";"2913";""
"Name2";"2914";""

I have tried it with sed, awk(with gsub) and pearl commands but each time instead of adding the ;"" to the end of each line it just replaces the first 3 characters of each line with it:

"Name1";"2913"

becomes

;""me1";"2913"

It is not limited to just ;"" it happends with anything i try to add at the end of the line. code i tried:

cat list | sed 's/$/;""/'
cat list | awk '{gsub(/$/,";\"\"")}1'

each with the same outcome of:

;""me1";"2913"
;""me2";"2914"

Why is this happening?


Solution

  • Looks like OP may have control M characters in OP's Input_file in that case could you please try following.

    awk -v s1="\"" 'BEGIN{FS=OFS=";"} {gsub(/\r/,"");$(NF+1)=s1 s1} 1'  Input_file
    

    2nd solution: With sed:

    sed 's/\r//g;s/$/;""/' Input_file
    

    Suggestions for OP's code:

    • We need not to use cat with awk or sed they are capable of reading Input_file by themselves.
    • You could have control M characters in your file so you could remove them by doing tr -d '\r' < Input_file > temp && mv temp Input_file OR directly run commands mentioned above to get rid of the carriage returns and get your output too.