0

I use sort to remove duplicate lines from text files, sort in alphabetical order, overwriting the files ({,} in the command):

sort -u -o $HOME/Documents/notes/URLs.txt{,}

How to add additional files to the mix, after URLs.txt? To illustrate with three additional ones:

$HOME/Documents/notes/{URLs.txt,Android.txt,mpv.txt,firefox.txt}

2 Answers 2

2

sort is sorting once all the input. So anytime we provide more than one file arguments to sort, we sort the concatenation of them. To sort separately the files and rewrite each one with the output, you have to invoke separate commands.

for f in URLs.txt Android.txt mpv.txt firefox.txt
do
    sort -u -o "$HOME/Documents/notes/$f"{,}
done

while this:

sort -u -o newfile "$HOME"/Documents/notes/*.txt

would sort the concatenation of all input files to newfile.

0

In zsh, I'd do:

for f (~/Documents/notes/(URLs|Android|mpv|firefox).txt(N)) sort -uo $f $f

(or sort -uo $f{,} if you want to golf it).

A bash equivalent would look like:

(shopt -s extglob nullglob
  for f in ~/Documents/notes/@(URLs|Android|mpv|firefox).txt; do
    sort -uo "$f" "$f"
  done
)

Those using globbing rather that brace expansion, so would only process those URLs.txt...firefox.txt if they actually exist.

With zsh, you can also add the . glob qualifier so that those files are processed only if they are regular files. With bash, you could add [[ -f $f && ! -L $f ]] || continue in the loop to skip the non-regular files.

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.