On OSX you can have tags which allows you to identify different categories of files. Here are two text files with different tags when viewed in Finder:

enter image description here

I have a large number of these files and have written a bash script to make several edits on these files. So, for instance I do:

$ sed 's/old text/new text/' file1.txt > /tmp/foo.txt
$ cp -p /tmp/foo.txt file1.txt

in which case I get the desired file content but loose the tags:

enter image description here

Question: How do I copy the tags from the original file to the edited file?

  • 2
    I believe that in this specific use case you can use "sed -i" for inline editing. This will keep tags in place. Not posting as answer as it doesn't answer part about copying tags and you can't always use inline editing. – pbm Mar 1 '15 at 23:41
  • @pbm: I was not able to get the "sed -i" to work on MacOS 10.9.5 and still keep the tags. The "-i" required a file extension that was used to rename the current file and hence the meta data was lost. – Peter Grill Mar 2 '15 at 1:26

When you run > /tmp/foo.txt, you are overwriting the contents of /tmp/foo.txt with the output of sed 's/old text/new text/' file1.txt. Since /tmp/foo.txt doesn't exist when you run this command, bash will create that file for you and then write it.

Then, when you use the -p flag to cp, you are copying the permissions and attributes of /tmp/foo.txt to file1.txt and overwriting it in the process.

Instead, what you want to do is overwrite the contents of file1.txt with the contents of /tmp/foo.txt, which should sound familiar. Run

sed 's/old text/new text/' file1.txt > /tmp/foo.txt
cat /tmp/foo.txt > file1.txt

Note that this doesn't copy any permissions or attributes from file1.txt to /tmp/foo.txt or vice versa - you are maintaining the existing metadata for file1.txt, but modifying the content.

In this specific instance, you could also just use sed -i as pbm suggested.

  • Glad it was so simple. – Peter Grill Mar 2 '15 at 1:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.