Open and write data to text file using bash/shell

2019-01-06 09:05发布

How can I write data to a text file automatically by shell scripting in Linux?

I was able to open the file. However, I don't know how to write data to it.

标签: bash shell
8条回答
在下西门庆
2楼-- · 2019-01-06 09:34

I like this answer:

cat > FILE.txt <<EOF

info code info 
...
EOF

but would suggest cat >> FILE.txt << EOF if you want just add something to the end of the file without wiping out what is already exists

Like this:

cat >> FILE.txt <<EOF

info code info 
...
EOF
查看更多
Lonely孤独者°
3楼-- · 2019-01-06 09:42

For environments where here documents are unavailable (Makefile, Dockerfile, etc) you can often use printf for a reasonably legible and efficient solution.

printf '%s\n' '#!/bin/sh' '# Second line' \
    '# Third line' \
    '# Conveniently mix single and double quotes, too' \
    "# Generated $(date)" \
    '# ^ the date command executes when the file is generated' \
    'for file in *; do' \
    '    echo "Found $file"' \
    'done' >outputfile
查看更多
乱世女痞
4楼-- · 2019-01-06 09:43
#!/bin/bash

cat > FILE.txt <<EOF

info code info 
info code info
info code info

EOF 
查看更多
做自己的国王
5楼-- · 2019-01-06 09:44
#!/bin/sh

FILE="/path/to/file"

/bin/cat <<EOM >$FILE
text1
text2
text3
text4
EOM
查看更多
三岁会撩人
6楼-- · 2019-01-06 09:50

I know this is a damn old question, but as the OP is about scripting, and for the fact that google brought me here, opening file descriptors for reading and writing at the same time should also be mentioned.

#!/bin/bash

# Open file descriptor (fd) 3 for read/write on a text file.
exec 3<> poem.txt

    # Let's print some text to fd 3
    echo "Roses are red" >&3
    echo "Violets are blue" >&3
    echo "Poems are cute" >&3
    echo "And so are you" >&3

# Close fd 3
exec 3>&-

Then cat the file on terminal

$ cat poem.txt
Roses are red
Violets are blue
Poems are cute
And so are you

This example causes file poem.txt to be open for reading and writing on file descriptor 3. It also shows that *nix boxes know more fd's then just stdin, stdout and stderr (fd 0,1,2). It actually holds a lot. Usually the max number of file descriptors the kernel can allocate can be found in /proc/sys/file-max or /proc/sys/fs/file-max but using any fd above 9 is dangerous as it could conflict with fd's used by the shell internally. So don't bother and only use fd's 0-9. If you need more the 9 file descriptors in a bash script you should use a different language anyways :)

Anyhow, fd's can be used in a lot of interesting ways.

查看更多
乱世女痞
7楼-- · 2019-01-06 09:54

You can redirect the output of a command to a file:

$ cat file > copy_file

or append to it

$ cat file >> copy_file

If you want to write directly the command is echo 'text'

$ echo 'Hello World' > file
查看更多
登录 后发表回答