Simply add the filenames as a new field: $ cut -f 2 HNs.bst_.lt_.txt | sort > HNusage/HNs.bst.lt/temp$ awk '{ print $2, $1, FILENAME }' *.txt | sort -k 1,1 | join - HNusage/HNs.bst.lt/temp
In the script: #!/bin/sh if [ -z "$2" ] then printf "Usage: $0 searched-domain-file file1 [file2 ...] " exit fi searched="$1" shift TMP=$(mktemp) trap "rm $TMP 2>/dev/null" 0 mkfifo $TMP cut -f 2 "$searched" | sort > $TMP & awk '{ print $2, $1, FILENAME }' "$@" | sort -k 1,1 | join - $TMP