Search code examples
bashshellubuntubash-completionyad

Removing "\n" character while writing into a file in Shell Script


Here i am taking the text input from the yad ui field and then i am writing that text into a solc.c but that text contains some \n characters , which are directly being written into solc.c

#!/bin/bash


language=$(yad --form --field="Select Language:CB" "C!C++" --button="OK:0" --button="Cancel:1" --width=300 --height=100)

if [ $? -eq 0 ]; then
  selected_language=$(echo "$language" | awk -F"|" '{print $1}')

  code=$(yad --form --field="Your Code:TXT" --title="Problem-A Solution" --button="OK:0" --button="Cancel:1" --width=800 --height=600)

  if [ $? -eq 0 ]; then
    if [ "$selected_language" = "C" ]; then
      "${code%?}" > "solc.c"  
      gcc solc.c
    elif [ "$selected_language" = "C++" ]; then
      "${code%?}" > "sol1.cpp"  
      g++ sol1.cpp
    else
      echo "Invalid language selected."
      exit 1
    fi

current solc.c

#include <stdio.h>\n\nint main() {\n    long long a, b;\n    scanf("%lld %lld", &a, &b);\n    printf("%lld\\n", a + b);\n    return 0;\n}\n
    return 0;\n }\n

expected :

#include <stdio.h>
int main() {
    long long a, b;
    scanf("%lld%lld", &a, &b);
    printf("%lld\n", a + b);
    return 0;
}

it worked sometime but for the same code it is not working now, and same it follows with sol1.cpp

Also mention ,if there is any other hacks to get rid of the \n being written into the file .


Solution

  • Just convert the string "\n" into the actual character \n:

    code=$(yad --form \
          --field="Your Code:TXT" \
          --title="Problem-A Solution" \
          --button="OK:0" \
          --button="Cancel:1" \
          --width=800 \
          --height=600 | 
             sed 's/\\n/\n/g')
    

    You can now do (you really don't want to use echo for unsanitized input like that, see here; and your code was trying to execute the $code variable instead of saving to a file)

    printf '%s\n' "$code" > solc.c