0

I want to know how to merge files with same names

For example I have following files in one folder:

1081713FHN-NA.one_.txt
1081713FHN-NA.second_.txt
1081713UEN-NA.one_.txt
1081713UEN-NA.second_.txt

And I want to merge first two into one output file and last two into another output file.

  • "merge" in what sense, exactly? do you want to concatenate the files, or interleave their lines, or paste them side-by-side, or something else? – steeldriver Jan 25 '16 at 23:17
1
for file in `ls`|cut -d"-" -f1
do
  cat ${file}-* > ${file}
done

this will cat the files with the same name prefix and send the output to the file with the same prefix, assuming you do not have any other stray files in the same directory you are in

1

Not knowing what you want the output to look like, it's a little difficult, but there's two steps as far as I can see it. Step one: picking the files, and step two: merging them. This is how I'd do step one.

# loop through your one_ files
for file1 in *-NA.one_.txt; do
    # get your second_ files
    file2=${file1/one_/second_}
    # cat them together
    cat $file1 $file2 > cat.$file1
    # or paste
    paste $file1 $file2
done
  • @don_crissti mostly because, "That's how I know how." It may be ugly, but it is also direct and transparent and won't catch any accidental files (perhaps "*-NA.three_.txt"). – 22degrees Jan 25 '16 at 23:32
  • No, that's really good. I didn't know that syntax existed. Thanks. – 22degrees Jan 25 '16 at 23:57
  • WOW! It looks like I am gonna use echo | sed a lot less frequently... Thanks again. – 22degrees Jan 26 '16 at 0:02

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.