Home > Enterprise >  How can I merge output from cat with existing file using sort command?
How can I merge output from cat with existing file using sort command?

Time:11-17

I currently have two files: anotherFile and myFile, which is being merged together to a result file, which is sorted. All this is 3 steps, however I want to be able to make it to a so called "one-liner"

Currently

#(script which creates 'anotherFile')
anotherFile > result
cat ./myFile | cut -f 1,2 >> result
sort -o result{,}

I want to be able to "one-liner" this, so I don't have to refer to result file 3 times!

cat ./myFile | cut -f 1,2 | xargs -I sort -m anotherFile {} > finalFile

I know the following above will not work since the {} is not an existing file.

CodePudding user response:

You can use {} to run your commands in a group, then pipe the output of that group through sort and redirect it into a file:

{
  ./anotherFileScript
  cut -f 1,2 ./myFile
} | sort > finalFile

If you must have it on a single line, you need some semicolons:

{ ./anotherFileScript; cut -f 1,2 ./myFile; } | sort > finalFile

Because cut can read from a file, you can eliminate the needless cat as well.

CodePudding user response:

Each file is referenced once:

{ ./anotherFileScript; cut -f1,2 myfile; } | sort > result
  •  Tags:  
  • bash
  • Related