How can I use a file in a command and redirect out

2018-12-31 07:24发布

Basically I want to take as input text from a file, remove a line from that file, and send the output back to the same file. Something along these lines if that makes it any clearer.

grep -v 'seg[0-9]\{1,\}\.[0-9]\{1\}' file_name > file_name

however, when I do this I end up with a blank file. Any thoughts?

标签: bash redirect io
13条回答
宁负流年不负卿
2楼-- · 2018-12-31 08:05

I usually use the tee program to do this:

grep -v 'seg[0-9]\{1,\}\.[0-9]\{1\}' file_name | tee file_name

It creates and removes a tempfile by itself.

查看更多
不再属于我。
3楼-- · 2018-12-31 08:08

You cannot do that because bash processes the redirections first, then executes the command. So by the time grep looks at file_name, it is already empty. You can use a temporary file though.

#!/bin/sh
tmpfile=$(mktemp)
grep -v 'seg[0-9]\{1,\}\.[0-9]\{1\}' file_name > ${tmpfile}
cat ${tmpfile} > file_name
rm -f ${tmpfile}

like that, consider using mktemp to create the tmpfile but note that it's not POSIX.

查看更多
孤独寂梦人
4楼-- · 2018-12-31 08:10

try this simple one

grep -v 'seg[0-9]\{1,\}\.[0-9]\{1\}' file_name | tee file_name

Your file will not be blank this time :) and your output is also printed to your terminal.

查看更多
残风、尘缘若梦
5楼-- · 2018-12-31 08:12

You can do that using process-substitution.

It's a bit of a hack though as bash opens all pipes asynchronously and we have to work around that using sleep so YMMV.

In your example:

grep -v 'seg[0-9]\{1,\}\.[0-9]\{1\}' file_name > >(sleep 1 && cat > file_name)
  • >(sleep 1 && cat > file_name) creates a temporary file that receives the output from grep
  • sleep 1 delays for a second to give grep time to parse the input file
  • finally cat > file_name writes the output
查看更多
笑指拈花
6楼-- · 2018-12-31 08:13

Use sponge for this kind of tasks. Its part of moreutils.

Try this command:

 grep -v 'seg[0-9]\{1,\}\.[0-9]\{1\}' file_name | sponge file_name
查看更多
梦寄多情
7楼-- · 2018-12-31 08:15

Use sed instead:

sed -i '/seg[0-9]\{1,\}\.[0-9]\{1\}/d' file_name
查看更多
登录 后发表回答