How can I use a file in a command and redirect output to the same file without truncating it?
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/shtmpfile=$(mktemp)grep -v 'seg[0-9]\{1,\}\.[0-9]\{1\}' file_name > ${tmpfile}cat ${tmpfile} > file_namerm -f ${tmpfile}
like that, consider using mktemp
to create the tmpfile but note that it's not POSIX.