Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse or repeat pipe input as arguments in command (example given)

Tags:

bash

shell

unix

I'll explain this problem with an example. Let's say I want to generate a list with two columns. Column 1 contains a file name and column 2 contains the md5 sum of that file.

This can be done using the following script:

for FILE in `ls -p | grep -v "/"`;
do
    printf "%s %s\n" "$FILE" `md5 -q "$FILE"`;
done;

Can this be done on a single line using pipes? I've tried using different combinations of sed, xargs and printf but I think I'm missing something. Here's one of my attempts:

ls -p | grep -v "/" | xargs -I FILE printf "%s %s\n" FILE `md5 -q FILE`

In that attempt, the FILE inside the backticks isn't substituted, which isn't really surprising.

Is this the kind of thing where I should just use a multi-line script? Since there's no logic or control flow, I feel that a one-liner should be possible and that perhaps I'm not using my tools properly or I haven't found the right tool.

Apologies for the title, I have no idea what to call this question.

like image 624
TimCinel Avatar asked Dec 20 '22 04:12

TimCinel


1 Answers

You can use md5sum, because I don't have md5 :)

ls -p | grep -v / | xargs md5sum | awk '{print $2,$1}'

and this may be a safer, more robust way:

find -maxdepth 1 -type f -exec md5sum {} \; | awk '{s=$2; $2=$1; $1=s;}1'

this should work with md5:

find -maxdepth 1 -type f -exec md5sum {} \; | sed 's/[^(]*(\([^)]*\)) =/\1/'
like image 157
perreal Avatar answered Apr 06 '23 01:04

perreal