How to echo "#" to files?

I'm writing a shell script that's going to copy the contents of some files to other files line by line. Suppose there're lines starting with #, such as #include<stdio.h> in .c files, when I tried to extracte that line with sed and echo it to another file, it couldn't work. I tried echo "#include<stdio.h>" >> myls.c in the shell, it couldn't write that content into myls.c. I think it's a parsing problem. Anyone know how to fix it?

PS: Suppose due to some requirements, I have to sed the lines and pipe them to echo, with which I write the extracted lines to another file.

For me it works fine :

$ echo "#include<stdio.h>" >> myls.c
$ cat myls.c
#include<stdio.h>
$

On which OS are you running?
Please provide a full example that demonstrate the issue

1 Like

Hi, I also tested it today and it works fine. But here I actually want to make it automatic, which means once take a file, we can go through each line of it, extract the line and echo it to another file. Here's the code:

 i=bin.sh
           echo "#!/bin/bash" > bundle.sh  
           number=`wc -l < $i`  #count the number of lines
           count=1
           while [ $count -le $number ]
           do
                 tmp=`sed -n "$count,1p" $i`   #extract the $count-th line
                 echo "echo $tmp" >> $i" >> bundle.sh
                 count=$(($count+1))
done

As you can see, the above code generates commands that will recreate file bin.sh, and exports these commands to another script called bundle.sh. So when bundle.sh is run, bin.sh is supposed to be generated. but if we encountered some special characters such as # and ; in bin.sh (the file to be recreated somewhere else), the second echo in echo "echo $tmp >> $i" >> bundle.sh won't be able to pass $tmp to $i because this command outputs: echo #contents or contents; >> bin.sh, codes after # will be interpreted as comments and ; will be interpreted as end of the line. Haven't found a way to figure it out yet. Many thanks.

Try echo "echo \"${tmp}\" >> $i" >> bundle.sh .

EDIT: But if a line in bin.sh has double-quotes in it you're still going to have a problem. You could transform the line first to escape any double-quotes (e.g. tmp=$(sed -n "$count,1p" $i | sed 's/"/\\"/g') ).

1 Like
Moderator comments were removed during original forum migration.
1 Like