Home > database >  Concatenate the output of 2 commands in the same line in Unix
Concatenate the output of 2 commands in the same line in Unix

Time:07-07

I have a command like below

md5sum test1.txt | cut -f 1 -d " " >> test.txt

I want output of the above result prefixed with File_CheckSum:

Expected output: File_CheckSum: <checksumvalue>

I tried as follows

echo 'File_Checksum:' >> test.txt | md5sum test.txt | cut -f 1 -d " " >> test.txt

but getting result as

File_Checksum:
adbch345wjlfjsafhals

I want the entire output in 1 line

File_Checksum: adbch345wjlfjsafhals

CodePudding user response:

echo writes a newline after it finishes writing its arguments. Some versions of echo allow a -n option to suppress this, but it's better to use printf instead.

You can use a command group to concatenate the the standard output of your two commands:

{ printf 'File_Checksum: '; md5sum test.txt | cut -f 1 -d " "; } >> test.txt

Note that there is a race condition here: you can theoretically write to test.txt before md5sum is done reading from it, causing you to checksum more data than you intended. (Your original command mentions test1.txt and test.txt as separate files, so it's not clear if you are really reading from and writing to the same file.)

CodePudding user response:

You can use command grouping to have a list of commands executed as a unit and redirect the output of the group at once:

{ printf 'File_Checksum: ';  md5sum test1.txt | cut -f 1 -d " " } >> test.txt

CodePudding user response:

printf "%s: %s\n" "File_Checksum:" "$(md5sum < test1.txt | cut ...)" > test.txt

Note that if you are trying to compute the hash of test.txt(the same file you are trying to write to), this changes things significantly.

Another option is:

{
    printf "File_Checksum: "
    md5sum ...
} > test.txt

Or:

exec > test.txt
printf "File_Checksum: "
md5sum ...

but be aware that all subsequent commands will also write their output to test.txt. The typical way to restore stdout is:

exec 3>&1
exec > test.txt # Redirect all subsequent commands to `test.txt`
printf "File_Checksum: "
md5sum ...
exec >&3  # Restore original stdout

CodePudding user response:

Operator && e.g. mkdir example && cd example

  • Related