Coder Perfect

Is it possible to write text to a file using the linux cat command?

Problem

Is something along these lines:

cat "Some text here." > myfile.txt

Possible? As a result, the contents of myfile.txt have been overwritten to:

Some text here.

This doesn’t work for me, but it doesn’t give me any errors either.

I’m looking for a cat-based solution (not vim/vim/emacs, etc.). Cat is shown in all online examples in connection with file inputs, not raw text…

Asked by IAmYourFaja

Solution #1

That is exactly what echo does:

echo "Some text here." > myfile.txt

Answered by Carl Norum

Solution #2

It appears that you are looking for a Here document.

cat > outfile.txt <<EOF
>some text
>to save
>EOF

Answered by gbrener

Solution #3

Here’s another option:

cat > outfile.txt
>Enter text
>to save press ctrl-d

Answered by stolen_leaves

Solution #4

For text file:

cat > output.txt <<EOF
some text
some lines
EOF

For PHP file:

cat > test.php <<PHP
<?php
echo "Test";
echo \$var;
?>
PHP

Answered by Le Khiem

Solution #5

To change my CPU settings, I use the following code to write raw text to files. I hope this information is useful. Script:

#!/bin/sh

cat > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor <<EOF
performance
EOF

cat > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor <<EOF
performance
EOF

The text “performance” is written to the two files stated earlier in the script. This sample overwrites files with old data.

To make this code executable, save it into a file (cpu update.sh) and run it:

chmod +x cpu_update.sh

After that, you can use the following command to start the script:

./cpu_update.sh

If you don’t want to overwrite the file’s old data, replace it.

cat > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor <<EOF

with

cat >> /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor <<EOF

This will append your text to the end of the file without overwriting any existing information.

Answered by Arahkun

Post is based on https://stackoverflow.com/questions/17115664/can-linux-cat-command-be-used-for-writing-text-to-file