Execute a command once per line of piped input?

ยท 478 words ยท 3 minute read

How to execute a command once per line of the piped input? or how to pipe each line at a time in linux terminal? is the same question.

There are two main ways to achieve this.

Using a while loop with read ๐Ÿ”—

This is a common approach for simple scenarios. Here’s the structure:

command | while read line; do
  # Perform some action on each line stored in the variable "$line"
  your_command "$line"
done
  • command: This is the command that generates the output you want to process line by line.
  • while read line: This loop iterates over each line of input read from standard input (stdin), which is piped from the previous command.
  • $line: This variable holds the current line being processed inside the loop.
  • your_command "$line": This is your desired command that will be executed on each line. Replace “your_command” with the actual command you want to run on each line.

Here is a more concise script.

command | while read -r line; do command "$line"; done  

Using xargs with -n1 option ๐Ÿ”—

xargs is a powerful tool for processing command-line arguments. The -n1 option tells xargs to execute the following command with a single argument at a time (each line). Here’s an example:

command | xargs -n1 your_command
  • This is similar to the previous method (while loop), but it’s more concise.
  • Be aware that xargs has some limitations, so refer to the man page (man xargs) for details if your use case is complex.

If you want to iterate over each line of a file, use it like this.

cat file... | xargs -n1 command

You can do the same without using pipe โ€” by using input redirection. Here is the script.

<file xargs -n1 command

Examples ๐Ÿ”—

How to show all tldr pages added in it? ๐Ÿ”—

Here is how I will script it.

  • get all titles of pages
  • pipe the result into xargs
  • iterate over each line of the piped input
  • execute the tldr command on each line (title of a page) to get its content into the stdout

Here is the script.

tldr -l | xargs -n1 tldr

note: the results are huge.

  • tldr -l lists all the titles of pages supported.
  • | xargs -n1 tldr gets the piped input line by line, and execute tldr on each line.

We can do the same thing using the while loop. Here is how.

tldr -l | while read -r line; do tldr "$line"; done

You can prettify the script to be like this.

tldr -l | while read -r line; do
    tldr "$line";
done

I hope this post helps you. If you know a person who can benefit from this information, send them a link of this post. If you want to get notified about new posts, follow me on YouTube , Twitter (x) , LinkedIn , Facebook , Telegram and GitHub .

Share: