>_ IzzyLab

Hands-on task

This task is step 12 of the course “Bash scripts: from a loop to a robust script”

Process files with spaces in their names

medium~5 min

The directory /root/data contains text files, and some have spaces in their names (my file.txt, two words.txt). Append the line PROCESSED to the end of every file with the .txt extension — including those with spaces. Don't touch keep.md. Do it with a single find … | xargs … pipeline that is resistant to spaces.

What you'll practise:
  • find
  • xargs
  • -print0
  • names with spaces
  • sed

Topic breakdown

A space is the standard argument separator, so the naive find | xargs pipeline tears names with spaces into pieces. The solution is to separate names not with a space but with a null byte: find can print them that way with the -print0 flag, and xargs can read them that way with the -0 flag. Having selected the right files by mask and fed them to such an xargs, you use as the handler command a tool that appends a line to the end of a file (for example sed with an address of the last line).

What's checked

  1. all .txt files (including those with spaces) processed
  2. keep.md untouched
  3. original contents preserved

What it looks like