Just wanted to share an alias I have in use and found it useful again. It’s a simple wrapper around xargs, which I always forget how to use properly, so I set up an alias for. All it does is operate on each line on stdout.

The arguments are interpreted as the command to execute. The only thing to remember is using the {} as a placeholder for the input line. Look in the examples to understand how its used.

# Pipe each line and execute a command. The "{}" will be replaced by the line.
#
# Example:
#   cat url.txt | foreach echo download {} to directory
#   ls -1 | foreach echo {}
#   find . -maxdepth 2 -type f -name 'M*' | foreach grep "USB" {}
alias foreach='xargs -d "\n" -I{}'

Useful for quickly operating on each line of a file (in example to download from list of urls) or do something with any stdout output line by line. Without remembering or typing a for loop in terminal.

  • bizdelnick@lemmy.ml
    link
    fedilink
    arrow-up
    2
    ·
    7 hours ago

    I almost never use xargs. The most common case for it is find, but it is easier to use its -exec option. Also, with find your example is incorrect. You forgot that file names can contain special characters, the newline character in particular. That’s why you need to pass -print0 option to find and -0 option to xargs.

    • thingsiplay@lemmy.mlOP
      link
      fedilink
      arrow-up
      1
      ·
      7 hours ago

      The example itself is not incorrect. It is just an example to show how the foreach works, not meant to be a full command on itself. Usually I don’t have newline characters in files either, so that is not a concern for myself. If I would want to be sure, then yes I would use zero option. But its good to point that out.