Village
Village

Reputation: 24433

Why does sed leave many files around?

I noticed many files in my directory, called "sedAbCdEf" or such.

Update:

I checked the scripts until I found one which makes the files. Here is some sample code:

#!/bin/bash
a=1
b=`wc -l < ./file1.txt`
while [ $a -le $b ]; do
    for i in `sed -n "$a"p ./file1.txt`; do
        for j in `sed -n "$a"p ./file2.txt`; do
            sed -i "s/$i/\nZZ$jZZ\n/g" ./file3.txt
            c=`grep -c $j file3.txt`
            if [ "$c" -ge 1 ]
            then
                echo $j >> file4.txt
                echo "Replaced "$i" with "$j" "$c" times ("$a"/"$b")."
            fi
                echo $i" not found ("$a"/"$b")."
            a=`expr $a + 1`
        done
    done
done

Upvotes: 13

Views: 12992

Answers (3)

jfs
jfs

Reputation: 414685

If you use -i option (it means make changes inplace) sed writes to a temporary file and then renames it to your file. Thus if operation is aborted your file is left unchanged.

You can see which files are opened, renamed with strace:

$ strace -e open,rename sed -i 's/a/b/g' somefile

Note: somefile is opened as readonly.

It seems there is no way to override the backup directory. GNU sed always writes in the file's directory (±symlinks). From sed/execute.c:

if (follow_symlinks)
  input->in_file_name = follow_symlink (name);
else
  input->in_file_name = name;

/* get the base name */
tmpdir = ck_strdup(input->in_file_name);
if ((p = strrchr(tmpdir, '/')))
  *(p + 1) = 0;
else
  strcpy(tmpdir, ".");

Prefix sed is hardcoded:

output_file.fp = ck_mkstemp (&input->out_file_name, tmpdir, "sed");

Upvotes: 5

cctan
cctan

Reputation: 2023

  • Why does it create these files?

sed -i "s/$i/\nZZ$jZZ\n/g" ./file3.txt

the -i option makes sed stores the stdout output into a temporary file.
After sed is done, it will rename this temp file to replace your original file3.txt.
If something is wrong when sed is running, these sedAbCdE temp files will be left there.

  • Do these have any value after a script has run?

Your old file is untouched. Usually no.

  • Can I send these files to another location , e.g. /tmp/?

Yes you can, see above.

Edit: see this for further reading.

Upvotes: 12

Xander
Xander

Reputation: 1715

This may be that, since you have used too much sed actions, and in a looped pattern, sed may be making tmp files which are not removed properly.

Sed creates un-deleteable files in Windows

Take a look at this post, sed have such an issue to be reported before. The better way is to make a script that removes the files, or create a function that remove all files that deletes all files with name starting with sed, (^sed* )like thing.

Upvotes: 2

Related Questions