I was trying to make an utility to read from stdin a list, then give it a command.

I made this script : (named consume_list)


set -euo pipefail

eval "hack() {  $@ ; }"

while read -r line
    hack "$line"
done < <(cat /dev/stdin)

And so I can wrap commands and ease the reading and making of scripts.

one poor example is to use bash substitutions on list (it is, for me, easier than sed, cut, tr etc.), as in :

cat log.txt | grep 'error' | consume_list 'echo ${1:20:10}'

which would

Is there a proper tool to achieve this ?

  • Can you give an example of text you want to extract ? i.e. a proper input/output example
    – Inian
    Mar 9 '18 at 10:42
  • One proper example would be extract all functions from one php class then write new files according to their names, and sort them in corresponding namespaces. (ie, split large files into namespaced little files, according to PSR-0 namespace style) Mar 9 '18 at 12:28

The “proper” tool to run a command on a series of lines from standard input (or anywhere else) is xargs:

grep error log.txt | xargs -r -d\\n -n 1 bash -c 'echo ${0:20:10}'

However in your example it’s really much better to use cut:

grep error log.txt | cut -c21-30
  • Oh, the first one is exactly that that's really neat. Didn't know of those well though options ! Mar 9 '18 at 12:30

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.