14
submitted 6 months ago by cm0002@toast.ooo to c/linux@programming.dev

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.

OC by @thingsiplay@lemmy.ml

top 5 comments
sorted by: hot top new old
[-] wildbus8979@sh.itjust.works 5 points 6 months ago

Don't steal people's content, at least crosspost properly.

[-] GrumpyBike1020@monero.town 2 points 6 months ago

See the link in this users profile which explains why

[-] wildbus8979@sh.itjust.works 1 points 6 months ago* (last edited 6 months ago)

I know why. The OP decided to post where they decided to post, it's frankly unethical to steal OP's shit and not crosspost properly.

I'm gonna continue downvoting this shit.

[-] secana@programming.dev 4 points 6 months ago

Cool little trick!

[-] stewie410@programming.dev 2 points 6 months ago* (last edited 6 months ago)

Or use a while-read loop anyway?

while read -r foo; do
  cmd "${foo}" 
done < <(ls -1)

(But don't script ls)

The find example should just use -exec grep "USB" {} + also, though -exec generally is the correct way to do this.

this post was submitted on 19 Feb 2026
14 points (81.8% liked)

Linux

14935 readers
172 users here now

A community for everything relating to the GNU/Linux operating system (except the memes!)

Also, check out:

Original icon base courtesy of lewing@isc.tamu.edu and The GIMP

founded 3 years ago
MODERATORS