Bash script to merge files into directory and delete originals

I am writing a very small bash script to merge some files into a directory.

Let's say I have a directory full of files:

 deb_1
 deb_2
 deb_3
 deb_4
 ...

      

I want to write a small bash script to combine them all into a file and delete the originals

So, I would run mrg deb* outputfile

, and the resulting directory would look like this:

 outputfile

      

Contains all deb files. I usually do thiscat deb* > outputfile && rm deb* -f

However, trying to convert this to a bash script is not entirely clear:

 #!bin/bash
 cat $1 > $2 && rm $1 -f

      

The lookup extension replaces $1-> deb_1,$2-> deb_2

+3


source to share


2 answers


Save the script as it is:

#!bin/bash
cat $1 > $2 && rm $1 -f

      



But apply single quotes to the first argument when you call it:

bash myscript.sh 'deb*' outputfile

      

+4


source


Along the line that @Eugeniu mentioned in his comment, something like

$ myscript outputfile files*

      

it would be possible given the following definition myscript

:

#!/bin/bash
OUTPUT="$1";shift
cat "$@" > "$OUTPUT" && rm "$@" -f

      

  • $@

    - a list of all command line arguments,
  • and "$@"

    - a list of command line arguments separately: "deb01" "deb02" "deb03"

    .
  • shift

    is used to remove the output file from the parameter list so that it does not appear in the extension $@

    .
  • cat

    concatenates the files together into your ouput file,
  • and the rm

    originals are deleted.

Using

General view of the team:

myscript OUTPUT [INPUT_FILE]...

      



In your case, you want to call it like

$ myscript outputfile deb_{1..4}/*

      

which grabs every file inside every directory as command line arguments before myscript

Alternative implementation

Using the last argument as an output file is possible (using $#

), but requires more work to remove the last parameter from $@

.

A simple way to overcome this - with the obvious script modification to use stdout - would be:

$ myscript input files... > outputfile

      

Since redirects are applied by the shell (cut and open outputfile

for input) before executing the command, it rm

will still be safe in the same sense as it is now - which is questionable IMO.

+1


source







All Articles